Python List remove()

This tutorial shows you everything you need to know to help you master the essential remove() method of the most fundamental container data type in the Python programming language.

Definition and Usage:

The list.remove(element) method removes the first occurrence of the element from an existing list. It does not, however, remove all occurrences of the element in the list!

Here’s a short example:

>>> lst = [1, 2, 99, 4, 99]
>>> lst.remove(99)
>>> lst
[1, 2, 4, 99]

In the first line of the example, you create the list lst. You then remove the integer element 99 from the list—but only its first occurrence. The result is the list with only four elements [1, 2, 4, 99].

Try it yourself:

Syntax:

You can call this method on each list object in Python. Here’s the syntax:

list.remove(element)

Arguments:

ArgumentDescription
elementObject you want to remove from the list. Only the first occurrence of the element is removed.

Return value:

The method list.remove(element) has return value None. It operates on an existing list and, therefore, doesn’t return a new list with the removed element

Video:

Code Puzzle:

Now you know the basics. Let’s deepen your understanding with a short code puzzle—can you solve it?

# Puzzle
presidents = ['Obama',
              'Trump',
              'Washington']
p2 = presidents[:2]
p2.remove('Trump')
print(presidents)
# What's the output of this code snippet?

You can check out the solution on the Finxter app.

Overview:

There are some alternative ways to remove elements from the list. See the overview table:

MethodDescription
lst.remove(x)Remove an element from the list (by value)
lst.pop()Remove an element from the list (by index) and return the element
lst.clear()Remove all elements from the list
del lst[3]Remove one or more elements from the list (by index or slice)
List comprehensionRemove all elements that meet a certain condition

Next, you’ll dive into each of those methods to gain some deep understanding.

Related articles:

Here’s your free PDF cheat sheet showing you all Python list methods on one simple page. Click the image to download the high-resolution PDF file, print it, and post it to your office wall:

remove() — Remove An Element by Value

To remove an element from the list, use the list.remove(element) method you’ve already seen previously:

>>> lst = ["Alice", 3, "alice", "Ann", 42]
>>> lst.remove("Ann")
>>> lst
['Alice', 3, 'alice', 42]

Try it yourself:

The method goes from left to right and removes the first occurrence of the element that’s equal to the one to be removed.

Removed Element Does Not Exist

If you’re trying to remove element x from the list but x does not exist in the list, Python throws a Value error:

>>> lst = ['Alice', 'Bob', 'Ann']
>>> lst.remove('Frank')
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    lst.remove('Frank')
ValueError: list.remove(x): x not in list

pop() — Remove An Element by Index

Per default, the pop() method removes the last element from the list and returns the element.

>>> lst = ['Alice', 'Bob', 'Ann']
>>> lst.pop()
'Ann'
>>> lst
['Alice', 'Bob']

But you can also define the optional index argument. In this case, you’ll remove the element at the given index—a little known Python secret!

>>> lst = ['Alice', 'Bob', 'Ann']
>>> lst.pop(1)
'Bob'
>>> lst
['Alice', 'Ann']

clear() — Remove All Elements

The clear() method simply removes all elements from a given list object.

>>> lst = ['Alice', 'Bob', 'Ann']
>>> lst.clear()
>>> lst
[]

del — Remove Elements by Index or Slice

This trick is also relatively unknown among Python beginners:

  • Use del lst[index] to remove the element at index.
  • Use del lst[start:stop] to remove all elements in the slice.
>>> lst = list(range(10))
>>> lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del lst[5]
>>> lst
[0, 1, 2, 3, 4, 6, 7, 8, 9]
>>> del lst[:4]
>>> lst
[4, 6, 7, 8, 9]

Related blog articles:

List Comprehension — Remove Elements Conditionally

Okay, this is kind of cheating because this method does not really remove elements from a list object. It merely creates a new list with some elements that meet your condition.

List comprehension is a compact way of creating lists. The simple formula is [ expression + context ].

  • Expression: What to do with each list element?
  • Context: What list elements to select? It consists of an arbitrary number of for and if statements.

The example [x for x in range(3)] creates the list [0, 1, 2].

You can also define a condition such as all odd values x%2==1 in the context part by using an if condition. This leads us to a way to remove all elements that do not meet a certain condition in a given list.

>>> lst = list(range(10))
>>> lst_new = [x for x in lst if x%2]
>>> lst_new
[1, 3, 5, 7, 9] 

While you iterate over the whole list lst, the condition x%2 requires that the elements are odd.

Related blog articles:

Python List remove() All

The list.remove(x) method only removes the first occurrence of element x from the list.

But what if you want to remove all occurrences of element x from a given list?

The answer is to use a simple loop:

lst = ['Ann', 'Ann', 'Ann', 'Alice', 'Ann', 'Bob']
x = 'Ann'

while x in lst:
    lst.remove(x)

print(lst)
# ['Alice', 'Bob']

You simply call the remove() method again and again until element x is not in the list anymore.

Python List Remove Duplicates

How to remove all duplicates of a given value in the list?

The naive approach is to go over each element and check whether this element already exists in the list. If so, remove it. However, this takes a few lines of code.

A shorter and more concise way is to create a dictionary out of the elements in the list. Each list element becomes a new key to the dictionary. All elements that occur multiple times will be assigned to the same key. The dictionary contains only unique keys—there cannot be multiple equal keys.

As dictionary values, you simply take dummy values (per default).

Related blog articles:

Then, you simply convert the dictionary back to a list throwing away the dummy values. As the dictionary keys stay in the same order, you don’t lose the order information of the original list elements.

Here’s the code:

>>> lst = [1, 1, 1, 3, 2, 5, 5, 2]
>>> dic = dict.fromkeys(lst)
>>> dic
{1: None, 3: None, 2: None, 5: None}
>>> duplicate_free = list(dic)
>>> duplicate_free
[1, 3, 2, 5]

Python List remove() If Exists

How to remove an element from a list—but only if it exists?

The problem is that if you try to remove an element from the list that doesn’t exist, Python throws a Value Error. You can avoid this by checking the membership of the element to be removed first:

>>> lst = ['Alice', 'Bob', 'Ann']
>>> lst.remove('Frank') if 'Frank' in lst else None
>>> lst
['Alice', 'Bob', 'Ann']

This makes use of the Python one-liner feature of conditional assignment (also called the ternary operator).

Related blog articles:

Python List remove() Thread Safe

Do you have a multiple threads that access your list at the same time? Then you need to be sure that the list operations (such as remove()) are actually thread safe.

In other words: can you call the remove() operation in two threads on the same list at the same time? (And can you be sure that the result is meaningful?)

The answer is yes (if you use the cPython implementation). The reason is Python’s global interpreter lock that ensures that a thread that’s currently working on it’s code will first finish its current basic Python operation as defined by the cPython implementation. Only if it terminates with this operation will the next thread be able to access the computational resource. This is ensured with a sophisticated locking scheme by the cPython implementation.

The only thing you need to know is that each basic operation in the cPython implementation is atomic. It’s executed wholly and at once before any other thread has the chance to run on the same virtual engine. Therefore, there are no race conditions. An example for such a race condition would be the following: the first thread reads a value from the list, the second threads overwrites the value, and the first thread overwrites the value again invalidating the second thread’s operation.

All cPython operations are thread-safe. But if you combine those operations into higher-level functions, those are not generally thread safe as they consist of many (possibly interleaving) operations.

Where to Go From Here?

The list.remove(element) method removes the first occurrence of element from the list.

You’ve learned the ins and outs of this important Python list method.

If you keep struggling with those basic Python commands and you feel stuck in your learning progress, I’ve got something for you: Python One-Liners (Amazon Link).

In the book, I’ll give you a thorough overview of critical computer science topics such as machine learning, regular expression, data science, NumPy, and Python basics—all in a single line of Python code!

Get the book from Amazon!

OFFICIAL BOOK DESCRIPTION: Python One-Liners will show readers how to perform useful tasks with one line of Python code. Following a brief Python refresher, the book covers essential advanced topics like slicing, list comprehension, broadcasting, lambda functions, algorithms, regular expressions, neural networks, logistic regression and more. Each of the 50 book sections introduces a problem to solve, walks the reader through the skills necessary to solve that problem, then provides a concise one-liner Python solution with a detailed explanation.