How do I get the last element of a list
Use negative indexing to access the first item from the back of your list
>>> my_list = [1,2,3,4] >>> print(my_list[-1]) 4
The use of negative indexing is the quickest and most pythonic solution to this problem. Pythonic in the sense that you are making use of the Python language since a lot of other programming languages do not offer negative indexing.
Remember that negative indexing is simpy another way of accessing the items of your sequence and is therefore not restricted to the last element. Simply keep in mind that you are starting from index 1 rather than 0.
>>> my_list = [1,2,3,4] >>> print(my_list[-2]) 3
Python will raise an IndexError exception if you try to access an item using an invalid index.
>>> my_list = [1,2,3,4] >>> my_list[-5] IndexError
Alternatively to negative indexing, you can also use len()
to achieve the same result. This approach is also quite common amongst other programming languages.
>>> my_list = [1,2,3,4] >>> print(len(my_list)) 4 >>> print(my_list[len(my_list)-1]) 4