How to Remove Item from a List with Python

Learn how to remove an item from a list with Python. Python makes this operation easy to perform; there are a few ways to achieve this in Python.

Card image cap

In this article, you will learn how to remove an item from a list with Python. Python makes this operation easy to perform; there are a few ways to achieve this in Python. We will see each approach and also examples of how to use the remove operation.

Plus, I have included some knowledge quiz questions to check your understanding as you navigate the post. Let’s dive in!

Remove Item By Value

In Python, you can remove an item of a specific value using the remove function. See below a fragment of the python documentation defining the .remove() method:

Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item. See the documentation here

The above means in case there are two items of the specific value to remove, one will remain in the List. If you call the remove operation to remove a value that doesn’t exist in the List the operation will raise an Exception, specifically a ValueError Exception.

Let’s see some examples of how to use the .remove() operation:

list=['cat','dog','bird','fish']
list.remove('cat')
print(list)

Output:

['dog', 'bird', 'fish']

As you can see in the example above, if you want to remove one value, for instance, cat, and there is just one occurrence of this value, the remove operation works fine.

However if the item is duplicated in the list, calling .remove() only once won’t be enough to delete the value cat from the list. See the example below:

list=['cat','cat','dog','bird','fish']
list.remove('cat')
print(list)

Output:

['cat', 'dog', 'bird', 'fish']

Therefore calling .remove() once won’t be sufficient in case you want to remove all occurrences. Let’s see in the next section how to approach this problem.

Knowledge checker

#1. What is the output of the following code? Solution at the end of the article

list=['Cat','dog','bird','fish']
list.remove('cat')
print(list)

A. ['dog', 'bird', 'fish']

B. ValueError: list.remove(x): x not in list

C. ['Cat','dog','bird','fish']

Remove all occurrences

We have seen how to remove one item from a list with Python. But how can we delete all occurrences of a given value, for instance, the value cat. One possible solution involves using handling Exception, or in other words, a Try-Except block.

As we have seen previously in the .remove() documentation, you know that an item doesn’t exist in a list when you try to call .remove(), and it returns a ValueError. Therefore you could wrap the remove statement with a while loop and keep calling the .remove() operation until you get an error. Then catch this error and update a flag, which is the exit condition of the loop.

In the example below, I have used a boolean variable called all_items_removed with an initial value false. This variable indicates that the element we want to delete was not completely removed yet. Then the loop and a try-except block. When the .remove() operation throws an Exception, the execution will jump to line 8. Since we got the exception, there is no more cat value, so we can update our flag to true to indicate all values equal to cat were removed. See this in action below:

list=['cat','cat','dog','bird','fish']
all_items_removed = False

while(not all_items_removed):
    try:
        list.remove('cat')
    except ValueError:
        all_items_removed = True
print(list)

Output:

['dog', 'bird', 'fish']

Knowledge checker

#2. What is the output of this code? Solution at the page bottom

list=['Cat','fish','dog','bird','fish']
list.remove('fish')
print(list)

A. ['Cat', 'dog', 'bird']

B. ['Cat','fish','dog','bird']

C. ['Cat', 'dog', 'bird', 'fish']

Remove Item By Index

So far, we have covered how to remove an item by value. Let’s see now how to delete by index. Python offers two mechanisms to delete an item by index: .pop() and del().

pop() operation

Here is a fragment of the python documentation of the .pop() operation:

Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. See the documentation here

Pretty straightforward. It’s worth noticing that a list is indexed starting by zero, meaning, for instance, if we have the following List: list=['cat','dog','bird','fish'] , cat is item #0, dog is item #1, and so on.

Therefore if we execute ['cat','dog','bird','fish'].remove(2), then the 'bird' item will be removed from the list. See another similar example below:

list=['cat','cat','dog','bird','fish']
list.pop(2) # dog
print(list)

Output:

['cat', 'cat', 'bird', 'fish']

And in case no index is specified, then the .pop operation removes the last item of the list, as illustrated below:

list=['cat','cat','dog','bird','fish']
list.pop() # last item
print(list)

Output:

['cat', 'cat', 'dog', 'bird']

del() operation

Another approach to delete an item from a list by index us using the del() operation. The del() method works recursively and deletes each target, from left to right. See the documentation here.

list=['cat','cat','dog','bird','fish']
del(list[0])
print(list)

Output:

['cat', 'dog', 'bird', 'fish']

This method could return an exception if you try to remove an index from the List. In that case, your program will return IndexError: list assignment index out of range.

Remove Multiple Items from List

There are a lot of possible operations you could perform on a list. Another operation is deleting multiples items from a list at once. You can achieve this using the del() combined with slicing. For instance, you could delete the elements from position 1 to position 4. See the example below:

list=['cat','cat','dog','bird','fish']
del(list[1:4])
print(list)

Output:

['cat', 'fish']

After the last deletion, two elements will remain in the list since the last position is not inclusive.

Or you could delete all elements from a specific position to the end of the list as follows:

list=['cat','cat','dog','bird','fish']
del(list[2:])
print(list)

Output:

['cat']

Those are two examples; you could use any form of slicing you need.

Knowledge checker

#3. What is the output of this code?

list=[1,6,7,2,9]
list.pop()
print(list)

A. [1, 6, 7, 2]

B. ValueError

C. [6, 7, 2, 9]

Remove all items from a List.

When it comes to removing and manipulating items in a list with Python, another really convenient operation is .clear(). Let’s see the definition provided in the python documentation:

Remove all items from the list. Equivalent to del a[:].

Therefore using the .clear() operation will leave you with an empty list, as you can see in the example below:

list=['cat','cat','dog','bird','fish']
list.clear()
print(list)

Output:

[]

Conclusion

To summarise, Python provides a few different methods to remove items from a list. You could delete items by value using .remove(), or by index using either .pop() or the del() method.

I hope you enjoy this tutorial and thank you so much for reading and supporting this blog! Happy Coding! 🙂

Solutions: 1.B, 2.C, 3.A

More Interesting Articles

Learn Ethical Hacking From Scratch Course

Become an ethical hacker that can hack computer systems like black hat hackers and secure them like security experts.

Project-Based Programming Introduction

Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications

100% Recommended book for Java Beginners

Unique lay-out and teaching programming style helping new concepts stick in your memory

90 Specific Ways to Write Better Python

Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples

Grow Your Java skills as a developer

Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.

Write Code as a Professional Developer

Excellent read for anyone who already know how to program and want to learn Best Practices

Every Developer should read this

Perfect book for anyone transitioning into the mid/mid-senior developer level

Great preparation for interviews

Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java