Skip to content
Home » Removing Elements from a List in Python

Removing Elements from a List in Python

Spread the love

You already know how to append and insert elements to list. You also know how to extend lists. Today we’ll learn how to remove elements from a list.

Here’s the video version of this article:

You can use the del statement to remove an element from a list. You just need to know the index of the element you want to remove:

>>> days = ["Monday", "Friday", "Saturday"]
>>> del days[1]
>>> days
['Monday', 'Saturday']

We can also combine the del statement with slicing to remove more elements:

>>> numbers = [4, 2, 6, 7, 16, 41, 54, 84, 21]
>>> del numbers[3:7]
>>> numbers
[4, 2, 6, 84, 21]

You can also use the del statement to remove the whole list:

>>> numbers = [4, 2, 6, 7, 16, 41, 54, 84, 21]
>>> del numbers

Now the list doesn’t exist anymore, that’s why we’re getting an error when trying to echo it:

>>> numbers
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'numbers' is not defined

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

You can use the method remove(x) to remove elements if you don’t know the index:

>>> days = ["Monday", "Friday", "Saturday"]
>>> days.remove("Friday")
>>> days
['Monday', 'Saturday']

The remove(x) method removes the first occurrence of x.

>>> scores = [20, 10, 20, 50, 70, 40]
>>> scores.remove(20)
>>> scores
[10, 20, 50, 70, 40]

>>> scores.remove(20)
>>> scores
[10, 50, 70, 40]

If the element is not found, we get an error:

>>> scores.remove(20)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

You can remove all the elements from a list either by using the del statement or by using the clear method. Suppose we have the following list:

>>> animals = ["tortoise", "reindeer", "rattlesnake"]

We can remove all the elements of the list, but not the list itself, using the del statement and slicing:

>>> del animals[:]
>>> animals
[]

Alternatively, we can use the clear method:

>>> animals = ["tortoise", "reindeer", "rattlesnake"]
>>> animals.clear()
>>> animals
[]

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply