How to find list intersection?

csguy11 picture csguy11 · Sep 13, 2010 · Viewed 235.7k times · Source
a = [1,2,3,4,5]
b = [1,3,5,6]
c = a and b
print c

actual output: [1,3,5,6] expected output: [1,3,5]

How can we achieve a boolean AND operation (list intersection) on two lists?

Answer

Mark Byers picture Mark Byers · Sep 13, 2010

If order is not important and you don't need to worry about duplicates then you can use set intersection:

>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> list(set(a) & set(b))
[1, 3, 5]