Eliminate All Instances of a Value from a List
Unlike the remove() method, which only removes the first occurrence of a value in a list, sometimes it's necessary to delete all instances of that value. Here's how to accomplish this removal:
Functional Strategy:
Python 3.x and 2.x offer several functional approaches:
Using filter() with a lambda function:
x = [1, 2, 3, 2, 2, 2, 3, 4] result = list(filter((2).__ne__, x)) # Python 3.x result = list(filter(lambda a: a != 2, x)) # Python 3.x and 2.x
Using list comprehension:
x = [1, 2, 3, 2, 2, 2, 3, 4] result = [i for i in x if i != 2]
The above is the detailed content of How Can I Remove All Occurrences of a Value from a Python List?. For more information, please follow other related articles on the PHP Chinese website!