Monday, January 29, 2018

list - Negative indexing in Python




I have one record in a list



>>> bob =['bob smith',42,30000,'software']


I am trying to get the last name 'smith' from this record



I use the below command:




>>> bob[0].split()[1]


It provides me 'smith'



But the book I am referring to use the below command:



>>> bob[0].split()[-1]



it also gives me same result 'smith'



Why do indexes [1] and [-1] provide the same result?


Answer



Python lists can be "back indexed" using negative indices. -1 signifies the last element, -2 signifies the second to last and so on. It just so happens that in your list of length 2, the last element is also the element at index 1.



Your book suggests using -1 because it is more appropriate from a logical standpoint. You don't want the item at index 1 per se, but rather the last element of the list, which is the last name. What if, for example, a middle name was also included? Then using an index of 1 would not work whereas an index of -1 would.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...