Get last element of a list in Python
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:
|
1 2 3 4 |
a = [1, 2, 3, 4, 5] # pass -1 to the subscript notation print('The last element of the list is:', a[-1]) |
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:
|
1 2 3 4 5 6 |
a = [] try: print('Last element of list is:', a[-1]) except IndexError: print('Index outside the bounds of the list') |
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:
|
1 2 3 4 5 6 |
a = [1, 2, 3, 4, 5] try: print('Last element of list is', a[len(a) - 1]) except IndexError: print('Index outside the bounds of the list') # 5 |
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:
|
1 2 3 4 5 6 7 8 |
a = [1, 2, 3, 4, 5] try: last_element = a.pop() print('Last element of list is', last_element) # 5 print('List is', a) # [1, 2, 3, 4] except IndexError: print('List is empty') |
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:
|
1 2 3 4 5 6 7 |
a = [1, 2, 3, 4, 5] try: list_iter = reversed(a) print('Last element of list is', next(list_iter)) except StopIteration: print('List is empty') |
That’s all about getting the last element of a list in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)