Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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

like image 328
ariel Avatar asked Feb 02 '10 18:02

ariel


4 Answers

If you want to modify the list in-place,

a[:] = [x for x in a if x != [1, 1]]
like image 138
Alex Martelli Avatar answered Nov 14 '22 06:11

Alex Martelli


Use a list comprehension:

[x for x in a if x != [1, 1]]
like image 35
Ignacio Vazquez-Abrams Avatar answered Nov 14 '22 07:11

Ignacio Vazquez-Abrams


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)
like image 9
ephemient Avatar answered Nov 14 '22 06:11

ephemient


def remAll(L, item):
    answer = []
    for i in L:
        if i!=item:
            answer.append(i)
    return answer
like image 7
inspectorG4dget Avatar answered Nov 14 '22 06:11

inspectorG4dget