![]() |
VOOZH | about |
In this article, we will learn about different ways of getting the last element of a list in Python.
For example, consider a list:
Input: list = [1, 3, 34, 12, 6]
Output: 6
Explanation: Last element of the list l in the above example is 6.
Let's explore various methods of doing it in Python:
The simplest and most efficient method uses negative indexing with a[-1]. In Python, we can use -1 as an index to access the last element directly.
5
We can also find the last element by using len() function. Find length of the list and then subtracting one to get the index of the last element.
5
Explanation:len(a) - 1 gives the index of the last item, which is then used to retrieve the value.
We can also find the last element by using len() function. Find length of the list and then subtracting one to get the index of the last element.
5
Explanation:len(a) - 1 gives the index of the last item, which is then used to retrieve the value.
Another interesting way to get the last element is by using slicing. If we slice the list with -1:, it returns a list with just the last element.
[5]
Explanation:
Another way to get the last element is by using pop() method. This method removes and returns the last element of the list.
5
Explanation:
Note: If you only want to read the value and not change the list, this method is not ideal.
Related articles: