
Get the last element of the list in Python
You can get the last element of a list by -1 index.
a = ['car', 'train', 'plane', 'rocket']
b = a[-1]
print(b) # rocket
As explained in Python List, it's possible to use a negative index in getting the value. Because the last index is equal to the length minus one, you can write the code like this code:
a = ['car', 'train', 'plane', 'rocket']
b = a[len(a) - 1]
print(b) # rocket
If the list has no element, the negative index raises the IndexError.
a = []
b = a[-1]
# IndexError: list index out of range
Comments
Powered by Markdown