In Python, how do you get the last element of a list?
To prevent IndexError: list index out of range
, use this syntax:
mylist = [1, 2, 3, 4]
# With None as default value:
value = mylist and mylist[-1]
# With specified default value (option 1):
value = mylist and mylist[-1] or 'default'
# With specified default value (option 2):
value = mylist[-1] if mylist else 'default'
You can also use the code below, if you do not want to get IndexError when the list is empty.
next(reversed(some_list), None)
lst[-1]
is the best approach, but with general iterables, consider more_itertools.last:
Code
import more_itertools as mit
mit.last([0, 1, 2, 3])
# 3
mit.last(iter([1, 2, 3]))
# 3
mit.last([], "some default")
# 'some default'
You can also do:
alist.pop()
It depends on what you want to do with your list because the pop()
method will delete the last element.
Another method:
some_list.reverse()
some_list[0]
If your str()
or list()
objects might end up being empty as so: astr = ''
or alist = []
, then you might want to use alist[-1:]
instead of alist[-1]
for object "sameness".
The significance of this is:
alist = []
alist[-1] # will generate an IndexError exception whereas
alist[-1:] # will return an empty list
astr = ''
astr[-1] # will generate an IndexError exception whereas
astr[-1:] # will return an empty str
Where the distinction being made is that returning an empty list object or empty str object is more "last element"-like then an exception object.