{"record":{"id":"373e29167735b157","repo":"TheAlgorithms/Python","slug":"string-lengths-must-match","errorCode":null,"errorMessage":"String lengths must match!","messagePattern":"String lengths must match!","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"strings/hamming_distance.py","lineNumber":26,"sourceCode":"        string1 (str): Sequence 1\n        string2 (str): Sequence 2\n\n    Returns:\n        int: Hamming distance\n\n    >>> hamming_distance(\"python\", \"python\")\n    0\n    >>> hamming_distance(\"karolin\", \"kathrin\")\n    3\n    >>> hamming_distance(\"00000\", \"11111\")\n    5\n    >>> hamming_distance(\"karolin\", \"kath\")\n    Traceback (most recent call last):\n      ...\n    ValueError: String lengths must match!\n    \"\"\"\n    if len(string1) != len(string2):\n        raise ValueError(\"String lengths must match!\")\n\n    count = 0\n\n    for char1, char2 in zip(string1, string2):\n        if char1 != char2:\n            count += 1\n\n    return count\n\n\nif __name__ == \"__main__\":\n    import doctest\n\n    doctest.testmod()\n","sourceCodeStart":8,"sourceCodeEnd":41,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/strings/hamming_distance.py#L8-L41","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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."],"exampleFix":"# before\nhamming_distance(\"karolin\", \"kath\")  # ValueError: String lengths must match!\n\n# after\nif len(string1) != len(string2):\n    raise ValueError(f\"inputs must be same length: {len(string1)} != {len(string2)}\")\nhdist = hamming_distance(string1, string2)","handlingStrategy":"validation","validationCode":"def safe_hamming_inputs(string1: str, string2: str) -> bool:\n    return isinstance(string1, str) and isinstance(string2, str) and len(string1) == len(string2)","typeGuard":"def is_equal_length_pair(a, b) -> bool:\n    return hasattr(a, \"__len__\") and hasattr(b, \"__len__\") and len(a) == len(b)","tryCatchPattern":"try:\n    dist = hamming_distance(string1, string2)\nexcept ValueError as exc:\n    if str(exc) == \"String lengths must match!\":\n        # handle length mismatch explicitly (pad, truncate, or report)\n        raise\n    raise","preventionTips":["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."],"tags":["python","strings","hamming-distance","validation","valueerror"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}