Tutorial

How to Compare Two Lists in Python (With Examples)

By 12 min read

Comparing two lists is one of the most common tasks in Python. You might need to find new user IDs since yesterday's export, check which files were deleted from a folder, or verify that a function returns the expected values. "Compare two lists" can mean several different things, though:

  • Which elements are in both lists, or only in one of them? (intersection and difference)
  • Are the two lists equal? (with or without caring about order)
  • Where exactly do they differ? (element by element, by position)

This guide covers all of them with runnable examples, explains the trade-offs, and ends with a summary table to help you pick the right method.

Just need a quick answer for two lists you already have? Paste them into the free Compare Two Lists tool – it shows items only in A, only in B and in both, without writing any code.


1. Using set (most common and fastest)

Use sets when you only care about which distinct values appear, not their order or how often they repeat.

list_a = [1, 2, 3, 4, 5]
list_b = [4, 5, 6, 7, 8]

set_a = set(list_a)
set_b = set(list_b)

# Common elements (intersection)
print(set_a & set_b)  # {4, 5}

# Elements only in A (difference)
print(set_a - set_b)  # {1, 2, 3}

# Elements only in B
print(set_b - set_a)  # {6, 7, 8}

# Elements in exactly one of the lists (symmetric difference)
print(set_a ^ set_b)  # {1, 2, 3, 6, 7, 8}

Sets are unordered, so the printed order may differ from the comments above. The operators have method equivalents – intersection(), difference() and symmetric_difference() – which also accept any iterable, so set_a.intersection(list_b) works without converting list_b first.

Pros: short, readable and very fast – a set lookup takes constant time on average. Cons: loses the original order and removes duplicates. Elements must be hashable (numbers, strings, tuples – not lists or dicts).


2. List comprehensions (keep order and duplicates)

Use a list comprehension when the order of list_a matters or when you want to keep duplicates.

list_a = [1, 2, 3, 4, 5, 5]  # contains a duplicate
list_b = [4, 5, 6, 7, 8]

set_b = set(list_b)  # build once for fast lookups

only_in_a = [x for x in list_a if x not in set_b]
print(only_in_a)  # [1, 2, 3]

in_both = [x for x in list_a if x in set_b]
print(in_both)  # [4, 5, 5]

Always check membership against a set, not the list itself. x in list_b scans the whole list on every check, so comparing two lists of 100,000 items that way takes billions of operations; with a set it is roughly 100,000 lookups.

To keep the order but drop duplicates in the result, use dict.fromkeys(), which preserves insertion order:

only_in_a_unique = list(dict.fromkeys(x for x in list_a if x not in set_b))

3. Using a for loop (easy to extend)

A plain loop does the same thing as a comprehension but is easier to extend with extra logic, logging or multiple output lists.

list_a = ["apple", "Banana", "cherry"]
list_b = ["banana", "date"]

lookup = {item.lower() for item in list_b}
only_in_a, in_both = [], []

for item in list_a:
    if item.lower() in lookup:  # case-insensitive comparison
        in_both.append(item)
    else:
        only_in_a.append(item)

print(only_in_a)  # ['apple', 'cherry']
print(in_both)    # ['Banana']

Normalizing values (lowercasing, stripping spaces with .strip()) before comparing is the most common fix when two lists "should" match but don't.


4. collections.Counter (compare how many times items appear)

Use Counter when duplicates matter – for example, comparing an order list against a shipment list where quantities count.

from collections import Counter

list_a = ["a", "b", "b", "c"]
list_b = ["b", "c", "d", "e"]

counter_a = Counter(list_a)
counter_b = Counter(list_b)

# Common elements, using the smaller count of each
print(list((counter_a & counter_b).elements()))  # ['b', 'c']

# What is left in A after removing B's items
print(list((counter_a - counter_b).elements()))  # ['a', 'b']

The second 'b' stays in the result because A contains it twice and B only once.


5. Check whether two lists are equal

The == operator compares lists element by element, in order:

print([1, 2, 3] == [1, 2, 3])  # True
print([1, 2, 3] == [3, 2, 1])  # False – same items, different order

To ignore the order, choose the comparison that matches how you treat duplicates:

from collections import Counter

a = [1, 2, 2, 3]
b = [3, 2, 1, 2]
c = [3, 2, 1]

# Same items with the same counts, any order
print(sorted(a) == sorted(b))    # True
print(Counter(a) == Counter(b))  # True – also works for unsortable items

# Same distinct items, duplicates ignored
print(set(a) == set(c))          # True
print(Counter(a) == Counter(c))  # False – a has two 2s

sorted() needs items that can be compared with each other; Counter only needs hashable items and runs in linear time, so it is usually the better choice for large lists.


6. Compare two lists element by element

When position matters – test results, time series, two CSV columns – compare items pairwise with zip():

expected = [10, 20, 30, 40]
actual   = [10, 25, 30, 45]

differences = [
    (i, e, a) for i, (e, a) in enumerate(zip(expected, actual)) if e != a
]
print(differences)  # [(1, 20, 25), (3, 40, 45)]

zip() stops at the shorter list. If the lists can have different lengths, use itertools.zip_longest so extra items are reported too:

from itertools import zip_longest

a = [1, 2, 3]
b = [1, 2, 3, 4, 5]

extra = [(i, x, y) for i, (x, y) in enumerate(zip_longest(a, b)) if x != y]
print(extra)  # [(3, None, 4), (4, None, 5)]

7. Compare lists of dictionaries

Dictionaries are not hashable, so you can't put them in a set directly. Compare them by a unique key such as id instead:

old = [{"id": 1, "name": "Ann"}, {"id": 2, "name": "Bob"}, {"id": 3, "name": "Cy"}]
new = [{"id": 2, "name": "Bob"}, {"id": 3, "name": "Cyrus"}, {"id": 4, "name": "Dee"}]

old_by_id = {row["id"]: row for row in old}
new_by_id = {row["id"]: row for row in new}

removed = [old_by_id[k] for k in old_by_id.keys() - new_by_id.keys()]
added   = [new_by_id[k] for k in new_by_id.keys() - old_by_id.keys()]
changed = [
    (old_by_id[k], new_by_id[k])
    for k in old_by_id.keys() & new_by_id.keys()
    if old_by_id[k] != new_by_id[k]
]

print(removed)  # [{'id': 1, 'name': 'Ann'}]
print(added)    # [{'id': 4, 'name': 'Dee'}]
print(changed)  # [({'id': 3, 'name': 'Cy'}, {'id': 3, 'name': 'Cyrus'})]

Dictionary key views (.keys()) support set operators directly, which keeps this short. If you need to compare whole records without a key, convert each one to a hashable form, for example tuple(sorted(row.items())).


8. Large datasets: pandas

For millions of rows, or data that already lives in CSV or Excel files, pandas can mark every row as only-left, only-right or both in one step:

import pandas as pd

df_a = pd.DataFrame({"email": ["ann@x.com", "bob@x.com", "cy@x.com"]})
df_b = pd.DataFrame({"email": ["bob@x.com", "cy@x.com", "dee@x.com"]})

merged = df_a.merge(df_b, on="email", how="outer", indicator=True)

only_in_a = merged.loc[merged["_merge"] == "left_only", "email"].tolist()
only_in_b = merged.loc[merged["_merge"] == "right_only", "email"].tolist()
in_both   = merged.loc[merged["_merge"] == "both", "email"].tolist()

print(only_in_a)  # ['ann@x.com']
print(only_in_b)  # ['dee@x.com']
print(in_both)    # ['bob@x.com', 'cy@x.com']

For a single column, df_a["email"].isin(df_b["email"]) returns a True/False mask you can use to filter rows. Clean the key column first (.str.strip().str.lower()) so that formatting differences don't hide matches.


Summary: which method should you use?

Goal Best method Keeps order? Keeps duplicates?
Common / different elements set operators No No
Differences in the original order List comprehension + set lookup Yes Yes
Custom rules (case-insensitive, trimming) for loop with normalized set Yes Yes
Compare counts of each item collections.Counter No Yes
Are the lists identical? == (ordered) or Counter (any order) – –
Differences by position zip() / zip_longest() Yes Yes
Lists of dictionaries Index by key, compare key views – –
Very large or tabular data pandas merge(indicator=True) – –

In most cases, start with sets: they are the fastest and the code is the shortest. Switch to a list comprehension when you need to keep order, to Counter when duplicates matter, and to pandas when the data is too large or already in a table. And when you just need to check two lists once, the online list comparison tool gets you the answer in seconds.

Tags

#Python#List Comparison#Tutorial

About the author

songshiqiangIndependent developer

Builds fun websites with AI tools.

Related Posts

Tutorial

How to Compare Two Lists in Google Sheets (Matches and Differences)

Compare two lists in Google Sheets with conditional formatting, COUNTIF, MATCH, XLOOKUP and FILTER: highlight matches, flag missing items, extract differences into a new list, and compare lists on different sheets.

9 min read
#Google Sheets#List Comparison#Tutorial
Read More
Tutorial

How to Compare Two Lists in Java (Common, Missing and Equal Elements)

Compare two lists in Java: check equality with or without order, find common elements with retainAll, find differences with removeAll or streams, compare lists of objects, and avoid the most common performance trap.

10 min read
#Java#List Comparison#Tutorial
Read More
Tutorial

How to Compare Two Lists in Excel (Find Matches and Differences)

Nine ways to compare two lists in Excel: highlight matches with conditional formatting, flag them with COUNTIF or MATCH, look them up with VLOOKUP or XLOOKUP, extract them with FILTER, compare row by row, and use Power Query for large data.

12 min read
#Excel#List Comparison#XLOOKUP#Tutorial
Read More