1

I want to subtract two lists and read this question Remove all the elements that occur in one list from another

# a-b
def subb(a,b):
    return [i for i in a if i not in b]

print subb([1,2,1,2],[1,2])

But the result is empty list which is not what I want,I think it should be [1,2],so I change my code,:

def subb(a,b):
    for i in b:
        if i in a:
            a.remove(i)
    return a

Now I want a Pythonic way to replace this function with a simple expression so that I can use the result in function easily.Is it possible?

Thanks.

Community
  • 1
  • 1
Mike
  • 19
  • 4

1 Answers1

1

If I don't misunderstand your meaning,this is what you want:

x, y = [1,2,1,2], [1,2]

print [j for j in x if not j in y or y.remove(j)]

Output:

[1, 2]

If you want the value of y to remain the same,you can try to use deepcopy,

from copy import deepcopy
yy = deepcopy(y)
print [j for j in x if not j in yy or yy.remove(j)]
McGrady
  • 10,869
  • 13
  • 47
  • 69