Skip to content

Python remove element from list by value | Example code

  • by

Use the remove() method to remove an element from a list by value in Python. But it does not remove all occurrences of a given element value. Use a list comprehension for that to remove e all values from a list.

Example remove an element from a list by value in Python

Simple example code.

Remove the first occurrence item by value

Removing “b” value from a given list.

a = ['a', 'b', 'c', 'd', 'b']
a.remove('b')
print(a)

Output:

Python remove element from list by value

Remove all occurrences

Using a list comprehension to remove all occurrences of a given value. For example, removing the ’20’ number.

a = [10, 20, 30, 40, 20, 30, 40, 20, 70, 20]
a = [x for x in a if x != 20]
print(a)

Output: [10, 30, 40, 30, 40, 70]

Do comment if you have any doubts and suggestions on this Python List topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading