python – How to get the last element of a list

python – How to get the last element of a list

some_list[-1] is the shortest and most Pythonic.

In fact, you can do much more with this syntax. The some_list[-n] syntax gets the nth-to-last element. So some_list[-1] gets the last element, some_list[-2] gets the second to last, etc, all the way down to some_list[-len(some_list)], which gives you the first element.

You can also set list elements in this way. For instance:

>>> some_list = [1, 2, 3]
>>> some_list[-1] = 5 # Set the last element
>>> some_list[-2] = 3 # Set the second to last element
>>> some_list
[1, 3, 5]

Note that getting a list item by index will raise an IndexError if the expected item doesnt exist. This means that some_list[-1] will raise an exception if some_list is empty, because an empty list cant have a last element.

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.

python – How to get the last element of a list

You can also do:

last_elem = alist.pop()

It depends on what you want to do with your list because the pop() method will delete the last element.

Leave a Reply

Your email address will not be published. Required fields are marked *