Intersection of Lists in Python

Find the common elements between two lists.

BeginnerList ProgramsExample 7 of 25
intersection-of-lists.py
1# Program to find intersection of two lists
2
3list1 = input("Enter first list elements: ").split()
4list2 = input("Enter second list elements: ").split()
5
6intersection = list(set(list1) & set(list2))
7
8print("Intersection:", intersection)

Output

Enter first list elements: 1 2 3
Enter second list elements: 2 3 4
Intersection: ['2', '3']

What's going on

We convert both lists to sets and use the & operator to compute their intersection.

After this program

If the idea is still fuzzy, read Day 5: Lists and List Methods in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 list programs, or see every topic on Python exercises.