Python remove element from list by value | Example code

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.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.