How to Remove the Last X Elements from a List in Python
Table of Contents
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:
PYTHONnumbers = [1, 2, 3, 4, 5]
We know that we can get the last element by using the bracket notation and passing in a -1
:
PYTHONnumbers = [1, 2, 3, 4, 5]
last_element = numbers[-1]
print(last_element)
BASH5
You can even get the last two elements by passing in a -2
:
PYTHONnumbers = [1, 2, 3, 4, 5]
print(numbers[-2:])
BASH[4, 5]
Using this syntax, we can define a new list that has the last elements removed from it, like so:
PYTHONnumbers = [1, 2, 3, 4, 5]
remove_last_elements = numbers[:-2]
print(remove_last_elements)
BASH[1, 2, 3]
In general, when you want to remove the last elements from a list, you can use this syntax:
PYTHONnumbers = [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.
PYTHONnumbers = [1, 2, 3, 4, 5]
del numbers[-1]
print(numbers)
BASH[1, 2, 3, 4]
Here is the general syntax for removing elements from a list:
PYTHONnumbers = [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!
- Getting Started with TypeScript
- Getting Started with Svelte
- How to Set Up Cron Jobs in Linux
- How to deploy a .NET app using Docker
- How to build a Discord bot using TypeScript
- How to deploy a Deno app using Docker
- How to deploy an Express app using Docker
- Getting Started with Handlebars.js
- Learn how to build a Slack Bot using Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React
- Getting Started with Vuex: Managing State in Vue