How to Remove the Last X Elements from a List in Python

Lists are a fundamental part of Python programming, as they are used to store many different types of data in a single variable.
One of the most common uses of lists is to store a collection of items and then add or remove items from the list.
In this post, we'll learn how you can remove the last elements from a list in Python.
Removing the Last Elements from a List by Slicing
Let's start off with a basic list:
numbers = [1, 2, 3, 4, 5]
We know that we can get the last element by using the bracket notation and passing in a -1
:
numbers = [1, 2, 3, 4, 5]
last_element = numbers[-1]
print(last_element)
5
You can even get the last two elements by passing in a -2
:
numbers = [1, 2, 3, 4, 5]
print(numbers[-2:])
[4, 5]
Using this syntax, we can define a new list that has the last elements removed from it, like so:
numbers = [1, 2, 3, 4, 5]
remove_last_elements = numbers[:-2]
print(remove_last_elements)
[1, 2, 3]
In general, when you want to remove the last elements from a list, you can use this syntax:
numbers = [1, 2, 3, 4, 5]
numbers = numbers[:-n or None]
print(numbers)
Simply replace n
with the number of elements you want to remove or use a variable for n
.
Removing the Last Elements from a List by Using the del Keyword
Another way you can remove elements from a list is by directly modifying the list.
You can use the del
keyword to remove elements from a list.
numbers = [1, 2, 3, 4, 5]
del numbers[-1]
print(numbers)
[1, 2, 3, 4]
Here is the general syntax for removing elements from a list:
numbers = [1, 2, 3, 4, 5]
del numbers[-n:]
As like with before, you can use a variable for n
or just directly replace n
with the number of elements you want to remove.
Conclusion
In this post, we learned the two different ways to remove the last elements from a list.
You can either utilize slicing to remove the last elements from a list, or you can use the del
keyword to directly modify the original list.
Hopefully, this has been helpful to you. Happy coding!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!