SACHIN GARG SACHIN GARG - 5 months ago 10
Python Question

Most pythonic way of getting index of the last list item

Given a list:

l1 = [0, 211, 576, 941, 1307, 1672, 2037]


What is the most pythonic way of getting the index of the last element of the list. Given that Python lists are zero-indexed, is it:

len(l1) - 1


Or, is it the following which uses Python's list operations:

l1.index(l1[-1])


Both return the same value, that is 6.

Answer

Only the first is correct:

>>> lst = [1, 2, 3, 4, 1]
>>> len(lst) - 1
4
>>> lst.index(lst[-1])
0

However it depends on what do you mean by "the index of the last element".

Note that index must traverse the whole list in order to provide an answer:

In [1]: %%timeit lst = list(range(100000))
   ...: lst.index(lst[-1])
   ...: 
1000 loops, best of 3: 1.82 ms per loop

In [2]: %%timeit lst = list(range(100000))
len(lst)-1
   ...: 
The slowest run took 80.20 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 3: 109 ns per loop

Note that the second timing is in nanoseconds versus milliseconds for the first one.