Find Common Elements of Two Lists in Python

Find elements that appear in both lists (preserving list order of the first).

BeginnerList ProgramsExample 18 of 25
find-common-elements-of-two-lists.py
Run in browser
1# Program to find common elements of two lists
2
3list1 = input("Enter first list elements: ").split()
4list2 = input("Enter second list elements: ").split()
5
6common = [x for x in list1 if x in list2]
7
8print("Common elements:", common)

Output

Enter first list elements: a b c d
Enter second list elements: c d e
Common elements: ['c', 'd']

What's going on

We iterate over the first list and select only those elements that also appear in the second list.