Get the last element of a list in Python

There are couple of simple ways to get the last element of a list in Python programming. One method just gets the last element. The other method gets the last element and removes it from the list. We will see the examples of both the methods here.

Without removing the last element

In this method you will just get the last element of the list. This will not remove the last element. It will be useful when you want just the last element and leave the list unchanged. Let’s see a sample code.

# A list
list_1 = ["a", "b", 1, 2, "e", "f"]

# Get the last element
last_element = list_1[-1]

print("\n", last_element)
print(list_1 , "\n")

Output

 f

['a', 'b', 1, 2, 'e', 'f']

By removing the last element

In this method you will remove and get the last element using the list.pop() method without an explicit index. Let’s see a sample code.

# A list
list_1 = ["a", "b", 1, 2, "e", "f"]

# Get the last element
last_element = list_1.pop()

print("\n", last_element)
print(list_1 , "\n")

Output

 f

['a', 'b', 1, 2, 'e']
Get the last element of a list in Python

More tips on lists in Python

Reference


Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.