Compare Two Lists in Python: Common, Only in First, Only in Second
A beginner-friendly helper that loops over two lists and returns items common to both, items only in the first list, and items only in the second list.
Python code
27 linesdef compare_lists(list1, list2):
common = []
only_in_first = []
only_in_second = []
for item in list1:
if item in list2:
common.append(item)
else:
only_in_first.append(item)
for item in list2:
if item not in list1:
only_in_second.append(item)
return common, only_in_first, only_in_second
if __name__ == "__main__":
fruits_a = ["apple", "banana", "cherry", "date"]
fruits_b = ["banana", "date", "fig", "grape"]
common, only_a, only_b = compare_lists(fruits_a, fruits_b)
print(f"Common items: {common}")
print(f"Only in first list: {only_a}")
print(f"Only in second list: {only_b}")
Output
Common items: ['banana', 'date']
Only in first list: ['apple', 'cherry']
Only in second list: ['fig', 'grape']
How it works
The function iterates over each item in list1 and checks membership in list2. If the item exists, it's added to common; otherwise, to only_in_first. A second loop over list2 catches items not in list1. This approach preserves the original order of items and works for any hashable data type. While membership checks (in) are O(n) per item, the code is clear and perfect for small to medium lists.
Common mistakes
- Forgetting to return all three lists — returning only one or two breaks the unpacked assignment.
- Using `set` operations and losing duplicate elements from the original lists.
- Assuming list1 and list2 have the same length — the function handles unequal lengths correctly only if you loop over both lists separately.
Variations
- Using set operations: common = list(set(list1) & set(list2)) for a faster but order-unpreserving result.
- Using list comprehensions: only_in_first = [item for item in list1 if item not in list2].
Real-world use cases
- Comparing two config file keys to find settings that differ between environments.
- Checking which items in a cart are already in a user's wishlist and which are new additions.
- Diffing two API responses to identify newly added and removed fields for migration scripts.
Sponsored
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
- Find Duplicate Elements in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.