This post will discuss how to get the last element of a list in Python.

1. Using negative indexing

Negative indexing allows us to access elements from the end of a list by using negative numbers as indices. Since the negative indices start from -1, a[-1] fetch the last item of list a, a[-2] fetch second last item of list the a, and so on. This is indeed the shortest and the most Pythonic solution. Following is a simple example demonstrating usage of this:

Download  Run Code

Output:

The last element of the list is: 5

 
If the list is empty or the index is out of range of a list, it will raise an IndexError. To be safe, you should always handle the error gracefully:

Download  Run Code

Output:

Index outside the bounds of the list

2. Using len() function

Another way to get the last element of a list in Python is to use the len() function, which returns the number of items in an object with a length attribute, such as a list. You can then use this number as an index to access the last element of a list by subtracting one from it. Here is an example of its usage:

Download  Run Code

3. Using pop() function

If you want to remove the last element of a list, you can use the pop() function. The pop() function is a built-in function that removes and returns an item from a list at a given index. If no index is specified, the pop() function removes and returns the last item of a list. Here is an example of its usage:

Download  Run Code

4. Using reversed() function

A fourth way to get the last element of a list is to get the reversed view of the list and access its first item, which is actually the last item of the list. The idea is to use the reversed() function to get an iterator that yields the items of a list in reverse order, and the next() function to get the first item from this iterator. For example:

Download  Run Code

That’s all about getting the last element of a list in Python.