Python Practice › List Programs › Program 11
Common elements of two lists
Write a Python program to get the common elements of two lists, in the order of the first list.
Input
[4, 5, 7, 9, 2, 1], [2, 5, 8, 3, 4, 7]
Output
[4, 5, 7, 2]
Approach
- Keep items of list1 that are in list2 (convert list2 to a set for speed).
Solution
list1 = [4, 5, 7, 9, 2, 1]list2 = [2, 5, 8, 3, 4, 7]lookup = set(list2)print([x for x in list1 if x in lookup])Output
[4, 5, 7, 2]
Line by line
Line 3
Membership checks on a set are fast, even for long lists.
Learn the concept
New to this topic? Read the lesson, then come back.