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
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.

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.