Python difflib: compare sequences and format diffs
Answer: difflib provides classes and functions for comparing sequences. SequenceMatcher compares pairs of sequences of any hashable type. unified_diff returns a compact unified diff. HtmlDiff can build a side-by-side HTML table.
Examples
import difflib
a = ["alpha", "beta", "gamma"]
b = ["alpha", "beta", "delta"]
print("".join(difflib.unified_diff(a, b, lineterm="")))
Rules
- Unified diffs show the lines that have changed plus a few lines of context.
- Sequence elements must be hashable for
SequenceMatcher.
See also
Claims
- id: C1 claim: difflib provides classes and functions for comparing sequences. source: S1 evidence: "This module provides classes and functions for comparing sequences"
- id: C2 claim: unified_diff returns a delta in unified diff format. source: S1 evidence: "return a delta (a generator generating the delta lines) in unified diff format"
- id: C3 claim: The rst source describes the same sequence comparison helpers. source: S2 evidence: "This module provides classes and functions for comparing sequences"
Sources
- [S1] difflib — Helpers for computing deltas. Python docs. https://docs.python.org/3/library/difflib.html . License: PSF-2.0. Accessed 2026-11-18.
- [S2] difflib.rst. CPython docs. https://raw.githubusercontent.com/python/cpython/main/Doc/library/difflib.rst . License: PSF-2.0. Accessed 2026-11-18.
License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: Python docs, difflib — Helpers for computing deltas; CPython docs, difflib.rst. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation. Text was condensed and changed from the originals.
License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Python docs, difflib — Helpers for computing deltas; CPython docs, difflib.rst. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation.
Cite this
iinventedlight. 2026. "Python difflib: compare sequences and format diffs." iinventedlight Library, iil:note:6tczwcej, version of 2026-11-18. https://iinventedlight.com/library/notes/python-difflib/. License: CC-BY-4.0.
@misc{iil_note_6tczwcej,
author = {{iinventedlight}},
title = {{Python difflib: compare sequences and format diffs}},
howpublished = {iinventedlight Library},
year = {2026},
date = {2026-11-18},
url = {https://iinventedlight.com/library/notes/python-difflib/},
note = {Permanent ID iil:note:6tczwcej. License: CC-BY-4.0.},
}
Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).
For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/python-difflib.md.