03-18-2020, 03:46 PM
Python List remove()
This tutorial shows you everything you need to know to help you master the essential method of the most fundamental container data type in the Python programming language.
Definition and Usage:
The method removes the first occurrence of the from an existing . It does not, however, remove all occurrences of the element in the list!
Here’s a short example:
In the first line of the example, you create the list. You then remove the integer element 99 from the list—but only its first occurrence. The result is the list with only four elements .
Try it yourself:
https://repl.it/repls/PotableOnerlookedD...?lite=true
Syntax:
You can call this method on each list object in Python. Here’s the syntax:
Arguments:
Argument |
Description
|
Object you want to remove from the list. Only the first occurrence of the element is removed.
Return value:
The method has return value . 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?
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:
Method |
Description
|
Remove an element from the list (by value)
|
Remove an element from the list (by index) and return the element
|
Remove all elements from the list
|
Remove one or more elements from the list (by index or slice)
List comprehension |
Remove all elements that meet a certain condition
Next, you’ll dive into each of those methods to gain some deep understanding.
remove() — Remove An Element by Value
To remove an element from the list, use the method you’ve already seen previously:
Try it yourself:
https://repl.it/repls/CurlyIdioticChief?lite=true
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:
pop() — Remove An Element by Index
https://repl.it/repls/CurlyIdioticChief?lite=true
Per default, the method removes the last element from the list and returns the element.
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!
clear() — Remove All Elements
https://repl.it/repls/TightWiseTechnician?lite=true
The method simply removes all elements from a given list object.
del — Remove Elements by Index or Slice
https://repl.it/repls/ClientsideForsaken...?lite=true
This trick is also relatively unknown among Python beginners:
Related blog articles:
List Comprehension — Remove Elements Conditionally
https://repl.it/repls/FabulousMadEquation?lite=true
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 ].
The example creates the list .
You can also define a condition such as all odd values 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.
While you iterate over the whole list, the condition requires that the elements are odd.
Related blog articles:
Python List remove() All
The method only removes the first occurrence of element from the list.
But what if you want to remove all occurrences of element from a given list?
The answer is to use a simple loop:
You simply call the method again and again until element is not in the list anymore.
Python List Remove Duplicates
https://repl.it/repls/GrandioseRemarkabl...?lite=true
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:
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. You can avoid this by checking the membership of the element to be removed first:
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) are actually thread safe.
In other words: can you call the 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 cPythonimplementation). 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 method removes the first occurrence of from the .
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.
This tutorial shows you everything you need to know to help you master the essential
Code:
remove()Definition and Usage:
The
Code:
list.remove(element)Code:
elementCode:
listHere’s a short example:
Code:
>>> 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
Code:
lstCode:
[1, 2, 4, 99]Try it yourself:
https://repl.it/repls/PotableOnerlookedD...?lite=true
Syntax:
You can call this method on each list object in Python. Here’s the syntax:
Code:
list.remove(element)Arguments:
Argument |
Description
Code:
elementObject you want to remove from the list. Only the first occurrence of the element is removed.
Return value:
The method
Code:
list.remove(element)Code:
NoneVideo:
Code Puzzle:
Now you know the basics. Let’s deepen your understanding with a short code puzzle—can you solve it?
Code:
# 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:
Method |
Description
Code:
lst.remove(x)Remove an element from the list (by value)
Code:
lst.pop()Remove an element from the list (by index) and return the element
Code:
lst.clear()Remove all elements from the list
Code:
del lst[3]Remove one or more elements from the list (by index or slice)
List comprehension |
Remove all elements that meet a certain condition
Next, you’ll dive into each of those methods to gain some deep understanding.
remove() — Remove An Element by Value
To remove an element from the list, use the
Code:
list.remove(element)Code:
>>> lst = ["Alice", 3, "alice", "Ann", 42]
>>> lst.remove("Ann")
>>> lst
['Alice', 3, 'alice', 42]Try it yourself:
https://repl.it/repls/CurlyIdioticChief?lite=true
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:
Code:
>>> 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 listhttps://repl.it/repls/CurlyIdioticChief?lite=true
Per default, the
Code:
pop()Code:
>>> 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!
Code:
>>> lst = ['Alice', 'Bob', 'Ann']
>>> lst.pop(1) 'Bob'
>>> lst
['Alice', 'Ann']https://repl.it/repls/TightWiseTechnician?lite=true
The
Code:
clear()Code:
>>> lst = ['Alice', 'Bob', 'Ann']
>>> lst.clear()
>>> lst
[]https://repl.it/repls/ClientsideForsaken...?lite=true
This trick is also relatively unknown among Python beginners:
- Use to remove the element at index.Code:
del lst[index]
- Use to remove all elements in the slice.Code:
del lst[start:stop]
Code:
>>> 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
https://repl.it/repls/FabulousMadEquation?lite=true
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
Code:
[x for x in range(3)]Code:
[0, 1, 2]You can also define a condition such as all odd values
Code:
x%2==1Code:
>>> 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
Code:
lstCode:
x%2Related blog articles:
Python List remove() All
The
Code:
list.remove(x)Code:
xBut what if you want to remove all occurrences of element
Code:
xThe answer is to use a simple loop:
Code:
lst = ['Ann', 'Ann', 'Ann', 'Alice', 'Ann', 'Bob']
x = 'Ann' while x in lst: lst.remove(x) print(lst)
# ['Alice', 'Bob']You simply call the
Code:
remove()Code:
xPython List Remove Duplicates
https://repl.it/repls/GrandioseRemarkabl...?lite=true
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:
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]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
Code:
Value ErrorCode:
>>> 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
Code:
remove()In other words: can you call the
Code:
remove()The answer is yes (if you use the cPythonimplementation). 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
Code:
list.remove(element)Code:
elementCode:
listYou’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.

