-2

How can I find the intersection of two lists in python? I've tried it with the in operator but am unsure as to how I do it without.

a = [2, 4, 6, 8, 10]
b = [4, 8, 12, 16, 20]
set(a) & set(b)

This should return [4, 8]

2 Answers2

0

You could convert your lists to sets, and then call intersection. A Python Set has intersection as a built-in method.

s1 = set(a)
s2 = set(b)
a.intersection(b)
# set([4,8])
Daniel
  • 2,345
  • 4
  • 19
  • 36
0

So you can get your intersection by using the example like below.

Intersection is already a first class part of set, you can directly use it

a = [2, 4, 6, 8, 10]
b = [4, 8, 12, 16, 20]
set(a).intersection(b)

The sets module provides classes for constructing and manipulating unordered collections of unique elements.Computing standard math operations on sets such as intersection, union etc.

Chetan_Vasudevan
  • 2,414
  • 1
  • 13
  • 34