How can I remove all instances of an element from a list in Python?

Viewed 82506

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]?

8 Answers

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
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)
Related