Skip to content

Python intersection of two lists | Example code

  • by

Use the set intersection() method to find the intersection of two lists in Python. First Convert the lists to sets using set(iterable) then use intersection() with these two sets to get the intersection.

Or use the & operator but need to convert both lists into sets first.

Example intersection of two lists in Python

A simple example code finds the intersection of list1 and list2.

list1 = [1, 2, 3]
list2 = [1, 3, 5]

res = set.intersection(set(list1), set(list2))

print(list(res))

Output:

Python intersection of two lists

The & operator can only be used to find the intersection of two sets, not lists.

list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]

intersection = set(list1) & set(list2)

print(intersection)

In this code, both list1 and list2 are converted into sets using the set() function. Then, the & operator is applied to the sets to find the common elements, resulting in {4, 5} as the intersection.

Do comment if you have any doubts or suggestions on this Python Python intersection code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading