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

Updated onbyAlan Morel
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:

PYTHON
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:

PYTHON
numbers = [1, 2, 3, 4, 5] last_element = numbers[-1] print(last_element)
BASH
5

You can even get the last two elements by passing in a -2:

PYTHON
numbers = [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:

PYTHON
numbers = [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:

PYTHON
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.

PYTHON
numbers = [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:

PYTHON
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!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.