tags:

views:

209

answers:

6

lets say I have a=[[1,1],[2,2],[1,1],[3,3],[1,1]] is there a function that remove all instances of [1,1]

thanks

+6  A: 

Use a list comprehension:

[x for x in a if x != [1, 1]]
Ignacio Vazquez-Abrams
I know writing `where` here is tempting, Ignacio, by analogy with SQL... but it doesn't work! You have to spell it `if`, as I did in my answer.
Alex Martelli
@Alex: Argh, yes, right, fixed.
Ignacio Vazquez-Abrams
+9  A: 

If you want to modify the list in-place,

a[:] = [x for x in a if x != [1, 1]]
Alex Martelli
+2  A: 
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([1,1],a)

Or more general:

def remove_all(elements, list):
    return filter(lambda x: x not in elements, list)

a = remove(([1,1],),a)
Felix Kling
Given what `list.remove` already does, I'd probably call this function `removeall`.
ephemient
.....Ok :).....
Felix Kling
A: 
def remAll(L, item):
    answer = []
    for i in L:
        if i!=item:
            answer.append(i)
    return answer
inspectorG4dget
+5  A: 

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)
ephemient
What's wrong with `filter([1,1].__ne__, a)`?
ΤΖΩΤΖΙΟΥ
@ΤΖΩΤΖΙΟΥ That works for `list`, but `__ne__` doesn't exist as a method on `int` or some other types in Python 2.x. This is fixed in Python 3.x, but for consistency...
ephemient
A: 
filter([1,1].__ne__,a)
gnibbler
I do prefer `functools.partial(operator.ne,[1,1])`, because (at least in Python 2.x) other types (`int`, for example) don't all have `__ne__`. That does appear to be fixed in Python 3, though: all types derive from `object`, which does have `__ne__`.
ephemient