The Python Oracle

Remove all occurrences of a value from a list?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC L Beethoven - Piano Sonata No 8 in C

--

Chapters
00:00 Question
00:27 Accepted answer (Score 665)
00:58 Answer 2 (Score 276)
01:14 Answer 3 (Score 140)
01:35 Answer 4 (Score 50)
01:50 Thank you

--

Full question
https://stackoverflow.com/questions/1157...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list

#avk47



ACCEPTED ANSWER

Score 723


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]

or

>>> [i for i in x if i != 2]

Python 2.x

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



ANSWER 2

Score 287


You can use a list comprehension:

def remove_values_from_list(the_list, val):
   return [value for value in the_list if value != val]

x = [1, 2, 3, 4, 2, 2, 3]
x = remove_values_from_list(x, 2)
print x
# [1, 3, 4, 3]



ANSWER 3

Score 148


You can use slice assignment if the original list must be modified, while still using an efficient list comprehension (or generator expression).

>>> x = [1, 2, 3, 4, 2, 2, 3]
>>> x[:] = (value for value in x if value != 2)
>>> x
[1, 3, 4, 3]



ANSWER 4

Score 53


Repeating the solution of the first post in a more abstract way:

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