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 browser1# Program to find common elements of two lists23list1 = input("Enter first list elements: ").split()4list2 = input("Enter second list elements: ").split()56common = [x for x in list1 if x in list2]78print("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.