PythonMastery
Python programs · Lists · beginner

Find common elements of two lists in Python

Find the items that appear in both of two lists in Python, keeping the order of the first list, and the shorter set & version.

The intersection of two lists is the items that appear in both. Here we find the people who are members of both clubs.

The program

python
python_club = ["Ada", "Linus", "Grace", "Alan"]
chess_club = ["Hedy", "Grace", "Ada", "Margaret"]

chess_members = set(chess_club)
both = [name for name in python_club if name in chess_members]

print("In both clubs:", both)
output
In both clubs: ['Ada', 'Grace']

How it works

Another way: the & operator

If you do not need the order, turn both lists into sets and use &:

python
a = [1, 2, 3, 4, 5, 5]
b = [5, 3, 7, 4, 6]

common = set(a) & set(b)
print(sorted(common))
output
[3, 4, 5]

Related programs: Set operations.

Learn the idea: Lists & Sequences, Sets: Unordered, Unique, Lightning Fast, Comprehensions: Lists, Dicts, Sets, Generators