More on accessing list elements: last element, negative indices

Suppose we have the list

In [1]:
L = ["a", "d", "c", "e", "f"]

How can we access its last element (i.e., "f")? The length of the list is len(L). That means the indices of the elements are 0, 1, 2, ..., len(L)-1. So the index of the last element is len(L)-1.

In [2]:
L[len(L)-1]
Out[2]:
'f'

Python allows you to use negative indices. L[-1] is the same as L[len(L)-1], L[-2] is the same as L[len(L)-2], and so on.

In general, L[-i] is the i-th element in L from the right.

In [3]:
L[-1]
Out[3]:
'f'
In [4]:
L[-2]
Out[4]:
'e'

Accessing the middle element

How do we access the middle element of L (assuming its length is odd?). L[len(L)//2] does the trick. (Note that we are using integer division here to compute len(L)//2 -- the index has to be an integer.)

Advice: it's hard to figure out if the index should be len(L)//2 + 1 or len(L)//2 - 1 or len(L)//2. Just try to figure out what it should be using a small example (e.g., a list of length 3 or 5).