Find Common Values in Two Python Lists
Which values appear in both lists? Turn them into sets and let & do the work.
- Converting lists to sets
- Intersection with &
- Sorting the result
- 1, 7
- 3, 5
- 2, 8
Values in both collections
The problem
Which students are in both clubs? Which products appear in both stores? Comparing every item of one list with every item of the other works for small lists but becomes slow, and duplicates make the result messy.
Think of it like this
A set intersection is like holding two transparent sheets with circled numbers over each other. Only the numbers circled on both sheets show through both circles. Everything else belongs to just one sheet.
set(left)📄 The first sheetset(right)📄 The second sheet&🔍 Lay them on top of each othersorted(...)📋 List the overlap in order: [3, 5]The intersection of two collections contains the values that appear in both of them; for sets it is written with &.
Key points
set(left)andset(right)turn the lists into sets.&keeps only the values present in both sets.sorted(...)turns the result back into an ordered list for printing.- 3 and 5 are the only values in both lists.
When should you use it?
- Finding common members, tags, products or IDs.
- Comparing two lists quickly, even when they are large.
- Practicing set operations.
When not to use it
- Duplicates matter, such as counting shared items in two shopping lists: use
Counterintersection instead. - You must keep the original order of the first list: filter it with a set lookup instead.
Example code
left = [1, 3, 5, 7]
right = [2, 3, 5, 8]
# Keep values that occur in both collections.
common = sorted(set(left) & set(right))
print(common)
Result of running the code
[3, 5]
Code explanation
set(left) and set(right) turn both lists into sets, which also removes any duplicates. The & operator keeps only the values that are in both sets, here 3 and 5. Sets have no order, so sorted() is used to return a list in a predictable order.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the input and predict the output before running.
- Handle empty or invalid input.
- Wrap the logic in a function and add more test cases.
Common mistakes
Comparing with nested loops
It works but is slow for large lists and repeats duplicates.
[x for x in left for y in right if x == y]
sorted(set(left) & set(right))
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges