Editor

Python Program to Find Common Elements in Two Lists

Beginner · Lists

The common elements of two lists are the values that appear in both of them, also called their intersection. This program checks each element of the first list against the second and collects each shared value once.

Program

common_elements.py
list1 = [1, 2, 3, 4, 5, 6, 4]
list2 = [4, 5, 6, 7, 8]
common = []
for item in list1:
# Keep it if list2 has it and we have not kept it already
if item in list2 and item not in common:
common.append(item)
print("List 1:", list1)
print("List 2:", list2)
if common:
print("Common elements:", common)
else:
print("The lists have no common elements")
Output
List 1: [1, 2, 3, 4, 5, 6, 4]
List 2: [4, 5, 6, 7, 8]
Common elements: [4, 5, 6]

How it works

  1. The loop takes each element of list1 in turn.
  2. item in list2 checks whether the second list also has that value.
  3. item not in common stops a repeated value, like the second 4, from being added twice.
  4. An empty list counts as false in an if, so the else branch runs when nothing is shared.

Other ways to write it

Using sets

Using sets
list1 = [1, 2, 3, 4, 5, 6, 4]
list2 = [4, 5, 6, 7, 8]
common = set(list1) & set(list2)
print("Common elements:", sorted(common))
print("Only in list 1:", sorted(set(list1) - set(list2)))
print("Only in list 2:", sorted(set(list2) - set(list1)))
Output
Common elements: [4, 5, 6]
Only in list 1: [1, 2, 3]
Only in list 2: [7, 8]

A set keeps one copy of each value, & gives the values in both sets and - the values in one but not the other. Sets do not keep order, so sorted() makes the output predictable.

Common to three lists

Common to three lists
class_a = ["Riya", "Aman", "Kabir", "Meera"]
class_b = ["Kabir", "Zoya", "Riya"]
class_c = ["Riya", "Kabir", "Arjun"]
in_all = set(class_a).intersection(class_b, class_c)
print("Names in all three lists:", sorted(in_all))
Output
Names in all three lists: ['Kabir', 'Riya']

intersection() accepts several lists at once and keeps only the values found in every one of them.

Try it yourself

Change the program to print the elements that are in either list but not in both.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises