Find Common List Values
Set intersection expresses membership in both collections.
What is Find Common List Values?
Set intersection expresses membership in both collections.
Find distinct values shared by two lists.
When should you use it?
- Learn Python syntax through a practical example.
- Build a foundation for larger programming problems.
- Test an idea quickly without a local setup.
Example code
main.py
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)
Expected output
[3, 5]
How it works
The ampersand operator intersects the two sets and sorted makes output deterministic.
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.