How to Get the Last Element of a List in Python

Getting the last element of a list is often counter-intuitive, but is sometimes needed for a logic we want to implement in Python. In this tutorial, we’ll explain the different methods you can use to extract the last element from a given list.

For example, we can have the following list:

my_list = [1,2,3,4,5]
Code language: Python (python)

And we want to store the last element (5) in a variable.

Use index position to extract the last element from a list

The most Pythonic way to achieve this operation is to use the my_list[-1] syntax. You may be familiar with the my_list[x] syntax to extract the xth element from a list (whose index starts from zero) and you can use a similar syntax to extract the xth last element.

  • my_list[-1] will get the last element
  • my_list[-2] will get the second to last element

Let’s apply our logic to our example:

my_list = [1,2,3,4,5] last_element = mylist[-1] print(f'The last element is {last_element}.')
Code language: Python (python)

Output:

The last element is 5.

Note that if your list is empty, your code will throw and IndexError error:

Traceback (most recent call last): File "file.py", line 2, in <module> last_element = my_list[-1] IndexError: list index out of range
Code language: Python (python)

To avoid this error, you can use a slighly more complex code to assign None to your variable is the list is empty.

my_list = [] last_element = mylist[-1] if my_list else None print(f'The last element is {last_element}.')
Code language: Python (python)

Output:

The last element is None.
Code language: Python (python)

Use the pop() method to get the last element of a list

If we look at the official documentation, we realize that the pop() method can be useful here. This method is used to remove an element by specifying its index. If we do not specify it, it returns the last element.

my_list = [1,2,3,4,5] last_element = my_list.pop() print(f'The last element is {last_element}.')
Code language: Python (python)

Output:

The last element is 5.

Be careful with this approach though because while the last_element variable will hold the expected value, you will alter your list (my_list in our case) and remove its last element.

Leave a Reply

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