Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all occurrences of a value from a list?

Tags:

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?

This is what I have in mind:

>>> remove_values_from_list([1, 2, 3, 4, 2, 2, 3], 2) [1, 3, 4, 3] 
like image 493
riza Avatar asked Jul 21 '09 03:07

riza


People also ask

How do I remove all occurrences from a character in Python?

Remove All Occurrences of a Character From a String in Python Using the translate() Method. We can also use the translate() method to remove characters from a string. The translate() method, when invoked on a string, takes a translation table as an input argument.


1 Answers

Functional approach:

Python 3.x

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

or

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

Python 2.x

>>> x = [1,2,3,2,2,2,3,4] >>> filter(lambda a: a != 2, x) [1, 3, 3, 4] 
like image 152
Mark Rushakoff Avatar answered Sep 20 '22 21:09

Mark Rushakoff