How can I remove all instances of an element from a list in Python? [duplicate]
Lets say I have a list a
:
a = [[1, 1], [2, 2], [1, 1], [3, 3], [1, 1]]
Is there a function that removes all instances of [1, 1]
?
If you want to modify the list in-place,
a[:] = [x for x in a if x != [1, 1]]
Use a list comprehension:
[x for x in a if x != [1, 1]]
Google finds Delete all items in the list, which includes gems such as
from functools import partial
from operator import ne
a = filter(partial(ne, [1, 1]), a)
def remAll(L, item):
answer = []
for i in L:
if i!=item:
answer.append(i)
return answer
Here is an easier alternative to Alex Martelli's answer:
a = [x for x in a if x != [1,1]]
new_list = filter(lambda x: x != [1,1], a)
Or as a function:
def remove_all(element, list):
return filter(lambda x: x != element, list)
a = remove_all([1,1],a)
Or more general:
def remove_all(elements, list):
return filter(lambda x: x not in elements, list)
a = remove_all(([1,1],),a)
filter([1,1].__ne__,a)
pure python no modules version, or no list comp version ( simpler to understand ?)
>>> x = [1, 1, 1, 1, 1, 1, 2, 3, 2]
>>> for item in xrange(x.count(1)):
... x.remove(1)
...
>>>
>>> x
[2, 3, 2]
can be made into a def pretty easily also
def removeThis(li,this):
for item in xrange(li.count(this)):
li.remove(this)
return li
精彩评论