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)
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)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.