The most recommended and Pythonic way to retrieve the last element of a list is to use negative indexing (list[-1]), provided the list is not empty.
main_list = [1, 2, 3, 4, 5] last_element = main_list[-1] print("The last element of the list is:", last_element) # Output: The last element of the list is: 5
If you start indexing backwards, the last index of the list will be -1, which is what we need to access the element. The -2 index refers to the second-to-last element, and so on.
This is the most efficient approach because it has O(1) time complexity.
What if the list is empty?
If the list is empty and you use negative indexing, it will throw the IndexError: list index out of range exception.
empty_list = [] last_element = empty_list[-1] print("The last element of the list is:", last_element) # Output: IndexError: list index out of range
To prevent this type of error, you can wrap it in a check to ensure the list is not empty. It is a fail-safe approach.
main_list = [] if main_list: last_element = main_list[-1] print("The last element of the list is:", last_element) else: print("List is empty") # Output: List is empty
List with a single element
If the input list has only one element, it will return that element because it becomes the last element.
main_list = [21] if main_list: last_element = main_list[-1] print("The last element of the list is:", last_element) else: print("List is empty") # Output: The last element of the list is: 21
Since there is only 21, it returns 21 as output.
Alternate approaches
Here are three alternate ways:
- Using list[len(list)-1]
- Using pop()
- Using slicing
Using list[len(list)-1]
Python has a built-in len() function that you can use to calculate the total length of the list and exactly pinpoint the last element.
main_list = [11, 21, 19, 48, 18] last_element = main_list[len(main_list)-1] print(last_element) # Output: 18
It explicitly uses the length to find the last position, but less concise than negative indexing.
If the list is empty, it will again raise the IndexError.
Using a list.pop()
The list.pop() method removes and returns the last element from the list.
Avoid using this method if you wish to retain all elements, as it permanently removes the last element.
main_list = [1, 2, 3, 4, 5] last_element = main_list.pop() print("The last element of the list is:", last_element) # Output: The last element of the list is: 5
Using slicing
By using a slice [-1:], you get the last element in a new list.
Since the output is a list, you can access the element itself using [0].
main_list = [1, 2, 3, 4, 5] last_element = main_list[-1:][0] print("The last element of the list is:", last_element) # Output: The last element of the list is: 5
That’s all!
proGrammer
what is I want to get last second elemnt of a list?
Krunal Lathiya
To retrieve the second-to-last element, simply pass an index of -2.