How to Compare Two Lists in Python
Set operations, list comprehension and pandas: how to get items only in one list, items in both, and the symmetric difference, with runnable snippets.
Updated 2026-11-29
Python has set operations built in, which makes list comparison short. The only trap is that sets drop duplicates and ignore order — fine for most comparisons, wrong when duplicates carry meaning.
Only in the first list
## Only in the second list
In both
## In either but not both
If you need to keep duplicates and order, use a list comprehension with a set for lookup:
This keeps every occurrence from `a` instead of collapsing to one. ## Case and whitespace Real data usually needs normalizing first:
Run the same normalization on both sides, or you will get false differences.
With pandas
If the lists live in DataFrames, isin is the idiomatic check:
For large files, pandas is faster and gives you the row context — the whole record, not just the key. ## When to skip the code If you are going to run this comparison once, pasting both lists into a browser tool takes ten seconds and produces the same three groups plus a CSV export. Reach for code when the comparison is part of a pipeline that runs repeatedly.
Compare your own lists
Paste two lists and see what is only in A, only in B, and in both — then export the result as CSV.
Open the list comparison tool →