How to find list intersection? How to find list intersection? python python

How to find list intersection?


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]


Using list comprehensions is a pretty obvious one for me. Not sure about performance, but at least things stay lists.

[x for x in a if x in b]

Or "all the x values that are in A, if the X value is in B".


If you convert the larger of the two lists into a set, you can get the intersection of that set with any iterable using intersection():

a = [1,2,3,4,5]b = [1,3,5,6]set(a).intersection(b)


matomo