Indexing and Slicing in Python

Indexing is simply referring to an element present in an iterable based on its position. While slicing is extracting element/elements from the iterable based on the index/indices value. Let's follow the below example for better understanding. Suppose 'v' is a string variable, saving value 'Python'.

v = 'Python'

Now the index start from '0' and increases as we move from left to right in the variable. In this case index value of 'P' is '0', index value of 'y' is '1', index value of 't' is '2' and so on.

Similarly, index value starts from '-1' and continues on decreasing as we move from right to left. In this case, the index value of extreme right element i.e. 'n' is '-1', index value of 'o' is '-2' and the index value continues accordingly.

 p   y   t   h   o   n
 0   1   2   3   4   5      #index value in positive terms
-6  -5  -4  -3  -2  -1      #index value in negative terms

So far, we have discussed how to refer an element of a variable, which is the definition of indexing. Now we can extract element/set of elements by the process called slicing. Follow closely!

We can extract 'P' by referring to its index position.

v[0] or v[-6] will yield output as 'P'

Similarly, we can extract set of elements say 'Pyth' by typing

v[0:4] will yield output as 'Pyth'

Note: In the above code '0' is the start index and '4' is the end index. In python, start index is included and end index is excluded. So by writing the above code we will extract elements with index value as 0, 1, 2 & 3.

Above, I have tried to explain Slicing and Indexing in brief. For further explanation on slicing, kindly follow my other article dedicated only to slicing. Hope, this helps.