riza riza - 6 months ago 27
Python Question

Remove all occurrences of a value from a Python list

In Python

remove()
will remove the first occurrence of value in a list.

How to remove all occurrences of a value from a list, without sorting the list?

This is what I have in mind.

>>> x = [1, 2, 3, 4, 2, 2, 3]
>>> def remove_values_from_list(the_list, val):
while val in the_list:
the_list.remove(val)
>>> remove_values_from_list(x, 2)
>>> x
[1, 3, 4, 3]

Answer

Functional approach:

2.x

>>> x = [1,2,3,2,2,2,3,4]
>>> filter(lambda a: a != 2, x)
[1, 3, 3, 4]

3.x

>>> list(filter((2).__ne__, x))
[1, 3, 3, 4]
Comments