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.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 14 views 0 copies

Python code

27 lines
Python 3.9+
def 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

stdout
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

  1. Using set operations: common = list(set(list1) & set(list2)) for a faster but order-unpreserving result.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.