In this post, we will go into a concept known as negative indices and negative slicing in Python. How do you utilize negative indices in Python? If you have not read my post on slicing in Python, I have given the link here. Let's create a list of numbers.
list_nos = [10,20,30,40,50,60]
list_nos[1:4]
--->[20,30,40]
list_nos[:2]
---> [10,20]
Let's say, we want to access last element in list.
list_nos[len(list_nos)-1]
--->[60]
Previous example can also be written as below
list_nos[-1]
---> [60]
If you want the second from last element
list_nos[-2]
---> [50]
If you want the third from last element
list_nos[-3]
---> [40]
You get the point!!!
Negative index can be sometimes easier to use than positive index. If you are still confused, I just made a helper image to help understand better.
How do you translate positive index to a negative index in Python?
Negative Index = Positive Index - length of data structure
So in our example list list_nos
-1 --> 5-6
-2 --> 4-6
-3 --> 3-6
-4 --> 2-6
-5 --> 1-6
-6 --> 0-6
Can slicing work with negative indices? If you do not know about slicing , you can read my previous post. Yes, slicing still works with negative indices. Recall that slicing is done in the format start:end:step
list_nos[-1:-6:-1]
---> [60, 50, 40, 30, 20]
Interpret the indexing as "Go from last index to the first index (but exclude the element at first index) with a step size of 1 in the negative direction" Note that the step size is negative. The element in the end index is not considered for retrieval. Element at index 0 which is 10 did not appear in the result. If you want element at index 0 , this is how you do
list_nos[-1::-1]
---> [60, 50, 40, 30, 20, 10]
If you carefully see the above result, you notice that you just reversed the list as well. Note that this is just a view of the list and we have not created a copy of the list. More on the topic "views" and copies later If you want alternate elements starting from the last element. Simple!!!
list_nos[-1:-6:-2]
---> [60, 40, 20]
Negative indices can be useful way to manipulate your Python lists. Always good to know about its functionality.
Comments
Post a Comment