fluttersmith/py-snippetsGitHub ↗

Hamming distance between strings

Count the positions at which two equal-length strings differ.

Strings#text#countingO(n) time✓ 3 examples pass on 3.11–3.14

How many characters changed between two codes, sequences or hashes of the same length?

hamming_distance.py✓ ruff · mypy --strict
def hamming_distance(a: str, b: str) -> int:
    """Return how many positions differ between two equal-length strings."""
    if len(a) != len(b):
        raise ValueError(f"strings must have equal length, got {len(a)} and {len(b)}")
    return sum(x != y for x, y in zip(a, b, strict=True))
  1. True counts as 1 in sum()
examples✓ 3 doctests · 3.11–3.14
passed on Python 3.11 to 3.14: >>> hamming_distance("karolin", "kathrin")3passed on Python 3.11 to 3.14: >>> hamming_distance("", "")0passed on Python 3.11 to 3.14: >>> hamming_distance("abc", "ab")Traceback (most recent call last):...ValueError: strings must have equal length, got 3 and 2
Edit the function or the examples and run the doctests here, on Python 3.14. Python loads only when you click (about 7 MB, cached after the first time).

How it works

  • zip(..., strict=True) walks both strings in step.
  • x != y is a bool, and sum counts each True as 1.
  • Different lengths raise ValueError: Hamming distance isn’t defined for them.

For integers, count the differing bits instead:

python
(a ^ b).bit_count()  # Python 3.10+

Complexity: O(n) time, O(1) space

Importfrom pysnippets.strings.hamming_distance import hamming_distanceNo dependencies: copy hamming_distance.py into your project, or clone the repo.

Adapted from hamming-distance in 30-seconds-of-python by the 30 seconds of code contributors, CC BY 4.0. Changed: Rewritten for strings; the integer version is shown below. Suggest an edit.