TheAlgorithms/Python · error · ValueError
String lengths must match!
Error message
String lengths must match!
What it means
This ValueError is raised by hamming_distance() in strings/hamming_distance.py when the two input strings have different lengths. The Hamming distance is only defined for strings of equal length, because it counts positions where corresponding symbols differ. The check at the top of the function (line 25-26) is the library's only guard, so any length mismatch fails before any comparison happens.
Source
Thrown at strings/hamming_distance.py:26
string1 (str): Sequence 1
string2 (str): Sequence 2
Returns:
int: Hamming distance
>>> hamming_distance("python", "python")
0
>>> hamming_distance("karolin", "kathrin")
3
>>> hamming_distance("00000", "11111")
5
>>> hamming_distance("karolin", "kath")
Traceback (most recent call last):
...
ValueError: String lengths must match!
"""
if len(string1) != len(string2):
raise ValueError("String lengths must match!")
count = 0
for char1, char2 in zip(string1, string2):
if char1 != char2:
count += 1
return count
if __name__ == "__main__":
import doctest
doctest.testmod()
View on GitHub (pinned to f5988cc097)
Solutions
- Verify both strings have the same length before calling: if len(a) != len(b): handle the mismatch in your own code.
- If the strings are expected to be equal but are not, inspect them for stray whitespace, encoding artifacts, or accidental slicing: print repr(a), repr(b), len(a), len(b).
- If you genuinely need to compare different-length strings, pad the shorter string to the longer length (e.g. with a sentinel char) or truncate both to min length, then call hamming_distance — but be aware this changes the metric's meaning.
- If your domain uses variable-length sequences, switch to a length-tolerant metric such as Levenshtein (edit) distance instead of Hamming distance.
- Wrap the call in try/except ValueError if a length mismatch is an expected, recoverable condition in your flow.
Example fix
# before
hamming_distance("karolin", "kath") # ValueError: String lengths must match!
# after
if len(string1) != len(string2):
raise ValueError(f"inputs must be same length: {len(string1)} != {len(string2)}")
hdist = hamming_distance(string1, string2) Defensive patterns
Strategy: validation
Validate before calling
def safe_hamming_inputs(string1: str, string2: str) -> bool:
return isinstance(string1, str) and isinstance(string2, str) and len(string1) == len(string2) Type guard
def is_equal_length_pair(a, b) -> bool:
return hasattr(a, "__len__") and hasattr(b, "__len__") and len(a) == len(b) Try / catch
try:
dist = hamming_distance(string1, string2)
except ValueError as exc:
if str(exc) == "String lengths must match!":
# handle length mismatch explicitly (pad, truncate, or report)
raise
raise Prevention
- Check len(a) == len(b) immediately after acquiring both strings (file load, API response, user input), not at comparison time.
- Log repr() and lengths of both inputs when validation fails so mismatches from whitespace/encoding are obvious.
- In tests, generate both strings from the same source or same length parameter.
- Prefer an edit-distance library if your inputs are not guaranteed equal length.
When it happens
Trigger: Calling hamming_distance(string1, string2) where len(string1) != len(string2), e.g. hamming_distance("karolin", "kath") raises ValueError: String lengths must match!. Any call with inputs of unequal length, even by one character, triggers it.
Common situations: Comparing user-supplied words or tokens of different lengths; comparing DNA/protein sequences where one has a truncation or trimming step applied; comparing strings loaded from different files or APIs where one side was normalized, sliced, or stripped; passing an empty string against a non-empty one.
Related errors
- surface_area_cube() only accepts non-negative values
- surface_area_cuboid() only accepts non-negative values
- surface_area_sphere() only accepts non-negative values
- surface_area_hemisphere() only accepts non-negative values
- surface_area_cone() only accepts non-negative values
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/373e29167735b157.
Report an issue: GitHub.