Python compare two lists and return differences

How to compare two lists in Python and return the differences, using sets, list comprehensions, Counter and positional checks, and how duplicates, order and normalization change the result.

The short answer

To get the items in one list that are missing from another, use a set difference when order and duplicates do not matter, or a list comprehension checked against a set when they do. To get the items that appear in only one of the two lists, in either direction, use the set symmetric difference operator (^). The examples below use Python 3 and only the standard library.

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

only_in_a = set(a) - set(b)    # {1, 2, 3}
only_in_b = set(b) - set(a)    # {6, 7}
in_either = set(a) ^ set(b)    # {1, 2, 3, 6, 7}

These lists are hypothetical. Before you pick a method, decide what counts as a "difference" for your data. That choice shapes the result more than the code does. Four questions settle it:

  • Direction: do you need items missing from one list, or the non-matching items from both?
  • Duplicates: should ["x", "x"] versus ["x"] count as a difference?
  • Order and position: does the original order matter, or do you need to know which index changed?
  • Equality: should "Apple" match "apple ", and are the items hashable values such as strings and numbers, or dictionaries and lists?

Return the unmatched values with set operations

Set operations are the most concise way to find the values that do not match. Use the minus operator (-) for a one-directional difference and the ^ operator for values that appear in exactly one list. The results are sets, so the original order is lost, duplicates collapse to one entry, and the display order is not guaranteed. If you need stable output, wrap the result in sorted().

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

print(sorted(set(a) - set(b)))   # [1, 2, 3]
print(sorted(set(a) ^ set(b)))   # [1, 2, 3, 6, 7]

Every item must be hashable. Strings, numbers and tuples work. Lists and dictionaries raise a TypeError. Also note that set membership uses ordinary equality, so 1, 1.0 and True are treated as the same value.

Remove matches while keeping order and duplicates

If the output needs to read like the original list, filter it with a list comprehension. Convert the other list to a set first, so that each membership check is a hash lookup and not a scan of the whole list. This removes the matching items and leaves everything else in its original position, repeats included.

a = ["apple", "banana", "apple", "cherry"]
b = ["banana", "date"]

b_set = set(b)
only_in_a = [x for x in a if x not in b_set]
print(only_in_a)   # ['apple', 'apple', 'cherry']

a_set = set(a)
only_in_b = [x for x in b if x not in a_set]
print(only_in_b)   # ['date']

To strip the matches out of the original list instead of building a new one, assign the result back with slice assignment: a[:] = [x for x in a if x not in b_set]. Any other references to the same list will then see the change as well.

Count duplicates as differences with Counter

Sets treat ["x", "x", "y"] and ["x", "y"] as identical. If the extra copy is the difference you care about, for example in inventory or log reconciliation, use collections.Counter. Subtracting one Counter from another keeps only the positive leftover counts.

from collections import Counter

a = ["x", "x", "y"]
b = ["x", "z"]

extra_in_a = Counter(a) - Counter(b)
print(extra_in_a)                    # Counter({'x': 1, 'y': 1})
print(list(extra_in_a.elements()))   # ['x', 'y']

extra_in_b = Counter(b) - Counter(a)
print(list(extra_in_b.elements()))   # ['z']

Find differences by position

Sometimes the question is which slots changed, not which values are missing. In that case, compare the lists element by element. zip() stops at the end of the shorter list. itertools.zip_longest() continues to the end of the longer one and fills the gaps with None, so it also reports extra trailing items.

from itertools import zip_longest

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

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

If None can appear as a real value in your lists, pass a distinct sentinel with fillvalue=object() so that padding cannot be mistaken for data.

Normalize text before matching

Exact comparison treats "Apple", "apple" and "apple " as three different values, which can inflate the list of differences with near-matches. Apply the same normalization to both sides before comparing, and keep the original values in the output so the results stay readable.

def norm(s):
    return s.strip().casefold()

a = ["Apple", " banana", "Cherry"]
b = ["apple", "banana "]

b_norm = {norm(s) for s in b}
print([s for s in a if norm(s) not in b_norm])   # ['Cherry']

Choose normalization rules on purpose. Each rule you add makes more items match, and it can hide differences that matter, such as case-sensitive product codes.

Compare lists of dictionaries or other unhashable items

Dictionaries cannot go into a set. The simplest workaround is a list comprehension that tests membership against the other list. This scans the second list for every item, so it slows down as both lists grow. When the records have a unique key, compare on that key with a set instead.

a = [{"id": 1, "name": "Ann"}, {"id": 2, "name": "Bo"}]
b = [{"id": 2, "name": "Bo"}]

# Whole-record match (linear scan of b for each item)
print([d for d in a if d not in b])           # [{'id': 1, 'name': 'Ann'}]

# Match on a key field
b_ids = {d["id"] for d in b}
print([d for d in a if d["id"] not in b_ids])  # [{'id': 1, 'name': 'Ann'}]

Matching on a key returns records whose id is absent from the other list. A record with the same id but a changed name will not appear. If edits count as differences, compare the full records or the specific fields you care about.

Print and check the result

Label each direction when you print, so it is clear which list each value came from. Then run a quick consistency check. Every item in the source list should end up either in the matches or in the differences.

a = ["apple", "banana", "apple", "cherry"]
b = ["banana", "date"]

b_set, a_set = set(b), set(a)
only_in_a = [x for x in a if x not in b_set]
only_in_b = [x for x in b if x not in a_set]
matches = [x for x in a if x in b_set]

print("Only in a:", only_in_a)   # Only in a: ['apple', 'apple', 'cherry']
print("Only in b:", only_in_b)   # Only in b: ['date']

assert len(matches) + len(only_in_a) == len(a)

If the differences look too large, inspect a few of the unmatched values with repr(). Hidden whitespace, case differences, or mixed types such as the string "1" and the integer 1 are the usual causes. For floating-point values, exact equality can fail on numbers that should match. In that case, compare them with math.isclose() rather than ==.

Picking the method for your requirement

Requirement | Method | Keeps order | Keeps duplicates
Unique values missing from one list | set(a) - set(b) | No | No
Non-matches from both lists | set(a) ^ set(b) | No | No
Remove matches, keep the list's shape | List comprehension against a set | Yes | Yes
Extra copies count as differences | Counter(a) - Counter(b) | Insertion order of first occurrence | Yes, as counts
Which positions changed | enumerate + zip_longest | Yes | Yes
Dictionaries or unhashable items | Comprehension, or a set of key fields | Yes | Yes

No timing measurements were available for this guide, so it makes no claims about relative speed beyond the general behavior described above. Set lookups avoid rescanning a list, while membership tests against a plain list do not. For large inputs, time the candidate approaches on your own data.