In this post, we'll learn how to remove the last N elements from a list in Python.
We'll go over the two best ways to do this.
For this example, we'll be using this list:
PYTHON
items = ["apple", "banana", "orange"]
Slicing
One way to remove the last N elements is by using slicing. Slicing supports a negative index, meaning we can use it to remove the last N elements from the list.
Let's see how we can use slicing to remove the last element:
In general, if you want to delete elements from a list, you can use this syntax:
PYTHON
del items[-n:]
Conclusion
In this post, we've seen two ways to remove the last N elements from a list. The first method using slicing keeps the original list intact, while the second method deletes the last N elements from the list.
Hopefully, you've found this post useful and you enjoyed reading it.
Happy coding!
To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!