Remove Last Element from a List in Python
Here are the 3 most common methods to remove the last element from a list in Python:
(1) Using pop()
The pop()
method removes and returns the element at the specified index from a list.
To remove the last element from a list using pop()
method, you can call it without providing an index, as it defaults to removing the last element from a list.
For example:
my_list = [5, 10, 15, 20]
removed_item = my_list.pop()
print(my_list) # Output: [5, 10, 15]
print(removed_item) # Output: 20
(2) Using del
The del
statement in Python is used to delete objects. However, you can use it to remove the last element from a list by specifying the index of the last element, which is -1
.
For example:
my_list = [5, 10, 15, 20]
del my_list[-1]
print(my_list) # Output: [5, 10, 15]
Python supports negative indexing, where -1
refers to the last element, -2
refers to the second-to-last element, and so on.
(3) Using slicing
Slicing allows you to extract a portion of a sequence (like a list, tuple, or string) by specifying a range of indices.
Slicing can also be used to remove the last element from the list by creating a new list that excludes the last element.
For example:
my_list = [5, 10, 15, 20]
new_list = my_list[:-1]
print(new_list) # Output: [5, 10, 15]
In the slice my_list[:-1]
, the start index is omitted so it defaults to 0
, meaing the slicing starts from the beginning of the list (start index is inclusive).
The end index -1
specifies that slice should include all elements up to, but not including, the last element (end index is exclusive).
Choosing the right method
Use pop()
if you need to remove and retrieve the last element for later use. It is the most efficient method.
Use del
if you need to remove the last element and don’t need to store or use it.
Use slicing when you need a new list with the last element removed without modifying the original list. It is the slowest method to remove the last element from the list.