19

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,132
  • 17
  • 67
  • 108

2 Answers2

44

use sets :

res = list(set(a)^set(b))
dugres
  • 11,893
  • 8
  • 44
  • 50
10

You can use sets learn more from here

print(set(a).difference(b))
Caleb Njiiri
  • 1,212
  • 1
  • 9
  • 18
  • 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
  • 2
    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