22

Possible Duplicate:
Python list subtraction operation

I want to remove the common elements between two lists. I mean something like this


a=[1,2,3,4,5,6,7,8]
b=[2,4,1]
# I want the result to be like
res=[3,5,6,7,8]

Is there any simple pythonic way to do this ?

Community
  • 1
  • 1
OneMoreError
  • 7,518
  • 20
  • 73
  • 112

2 Answers2

49

use sets :

res = list(set(a)^set(b))
dugres
  • 12,613
  • 8
  • 46
  • 51
12

You can use sets learn more from here

print(set(a).difference(b))
Caleb Njiiri
  • 1,563
  • 1
  • 11
  • 20
  • 1
    `list(set(a).difference(b))` make ordered list. What if i donot want ordered list and want same as list a, just removed common elements – Hitesh May 30 '18 at 11:26
  • 7
    may be `x = [i for i in x if i not in y] ` good choice. – Hitesh May 30 '18 at 11:44
  • 3
    This doesn't quite answer the OP as stated... but this DOES answer the question I was actually looking for, and is a useful answer. This returns only the elements of a that are not in b (OP asked for non-dupe elements in both a and b) – G__ Oct 27 '18 at 04:24