How to Get the Last Element of a List in Python?

A Python list is an ordered collection of items. It means the list items can be accessed using the list indexes.

In this article, I will show you three different methods that can be used to get the last element of a list. These methods are as follows:


Get the Last Element of a List Using the len() Function

The len() function returns the length of a sequence in Python. As we know the list index starts from 0. It means the index of the last element of the list will be its length – 1.

This is how you can get the last element:

numbers = [1, 2, 3, 4, 5]
length = len(numbers)

last_element = numbers[length - 1]
print('Last element is: ', last_element)

Output:

Last element is:  5

Get the Last Element of a List Using Negative Indexing

Python lists do also support negative indexing.

In negative indexing, the list indexes start from the end of the list. The index of the last element is -1, the index of the second last element is -2, and so on.

This is how you can get the last element using negative indexing:

numbers = [1, 2, 3, 4, 5]

last_element = numbers[-1]
print('Last element is: ', last_element)

Output:

Last element is:  5

Get the Last Element of a List Using the pop() Method

The built-in pop() method can also be used to get the last element of a list. The list.pop() method removes the last element from the list and returns it.

As this approach removes the last element from the list, therefore, you should only use this approach only when the list you are working with will not be reused.

Example:

numbers = [1, 2, 3, 4, 5]

last_element = numbers.pop()
print('Last element is: ', last_element)

print('List after pop(): ', numbers)

Output:

Last element is:  5
List after pop():  [1, 2, 3, 4]

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts