Monday, 29 January 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

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...