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
List 1: [1, 2, 3, 4, 5, 6, 4] List 2: [4, 5, 6, 7, 8] Common elements: [4, 5, 6]
How it works
- The loop takes each element of
list1in turn. item in list2checks whether the second list also has that value.item not in commonstops a repeated value, like the second 4, from being added twice.- An empty list counts as false in an
if, so theelsebranch runs when nothing is shared.
Other ways to write it
Using sets
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
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.
Related programs
- Merge Two Lists
- Find Duplicates in a List
- Remove Duplicates from a List
- Search for an Element in a List
- Find the Largest and Smallest Number in a List
- Swap Elements at Even and Odd Positions in a List
- Find the Second Largest Number in a List
- a Menu-Driven List
- Find the Sum of Elements in a List
- Reverse a List
All Python programs · CBSE class 12 practical file · Python exercises