Python: Remove last element from a list

This article will discuss different ways to delete the last element from a list in Python.


Table of Contents

Remove the last element from a list in Python using the pop() function

In Python, the list class provides a function pop(index); it accepts an optional argument index and deletes the element at the given index. If no argument is provided, then it, by default, deletes the last element of the list. Let’s use this function to remove the last element from a list,

list_of_num = [51, 52, 53, 54, 55, 56, 57, 58, 59]

# Remove last element from list
list_of_num.pop()

print(list_of_num)

Output:

[51, 52, 53, 54, 55, 56, 57, 58]

As we didn’t provide the index argument in the pop() function, therefore it deleted the last item of the list in place.

Remove the last element from a list in Python using slicing

We can slice the list to remove the last element. To slice a list, provide start and end index in the subscript operator. For example,

list[start: end]

It will select the elements from index positions start to end-1. If the start index is not provided, it selects from the first element of the list, and if the end index is not provided, it selects until the end of the list.

If the list has N elements, then slice it to select elements from index position 0 to N-1. In the list, we can also select elements using negative indexing, and the index of the last element in the list is -1. So, to delete the last element from a list, select the elements from start to -1. For example,

list_of_num = [51, 52, 53, 54, 55, 56, 57, 58, 59]

# Remove last element from list
list_of_num = list_of_num[:-1]

print(list_of_num)

Output:

[51, 52, 53, 54, 55, 56, 57, 58]

It deleted the last element from the list.

Remove the last element from a list in Python using del keyword

To delete the last element from a list, select the last element using negative indexing, and give it to the del keyword to delete it. For example,

list_of_num = [51, 52, 53, 54, 55, 56, 57, 58, 59]

# Remove last element from list
del list_of_num[-1]

print(list_of_num)

Output:

[51, 52, 53, 54, 55, 56, 57, 58]

It deleted the last item from the list.

Summary

We learned about different ways to delete the last element from a list in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

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

Scroll to Top