Finding the last element of a list is an important task in Python.
The last element of a list can be found with various methods, including using built-in functions like len() and reversed(). In this article, we’ll explore 3 different approaches to finding the last element or index position of a given list in Python.
Using Python built-in function: len()
This method is very simple, and it uses built-in Python functions:
import the list
print the list
print the length of the list
print the last element of the list
Using Python built-in function index()
The Python built-in function index() can be used to find the index of the last item in a list.
The index() function returns indices (or positions) of array elements.
It takes two arguments: an array, and a value to search for in that array.
If you pass it an empty list as second argument, it will return -1, indicating that no items were found before they were all exhausted.
Using Python built-in function reversed()
The reversed() function can be used to find the last element of a list. It takes a list as an argument and returns the last element of that list.
For example:
reversed(my_list)
Conclusion
In this article, we learned three ways to find the last element of a list in Python. The first method was using the built-in function len(). The second method was using index(), which returns the index of last element in the list. Finally, we used reversed() function to iterate through the list from end to beginning.