How to Remove the Last N Elements of a List in Python
Table of Contents
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:
PYTHONitems = ["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:
PYTHONitems = ["apple", "banana", "orange"]
print(items[:-1]) # ['apple', 'banana']
In general, you can use this syntax to remove the last N elements from a list:
PYTHONitems = items[:-N]
Deleting
Another way to remove the last N elements is by just deleting it from the list.
Whereas before, we did not modify the original list, by deleting, we are actually removing the last N elements from the list.
To delete, you can use the del
keyword, followed by the elements you want deleted.
Back to our earlier example:
PYTHONitems = ["apple", "banana", "orange"]
del items[-1]
print(items) # ['apple', 'banana']
In general, if you want to delete elements from a list, you can use this syntax:
PYTHONdel 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!
- Create an RSS Reader in Node
- How to deploy a .NET app using Docker
- How to build a Discord bot using TypeScript
- How to deploy a MySQL Server using Docker
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Using Push.js to Display Web Browser Notifications
- Getting Started with React
- Setting Up Stylus CSS Preprocessor
- Setting Up a Local Web Server using Node.js