Hamming distance using SciPy

The Hamming distance describes how many elements differ between two strings or one-dimensional arrays of same length. The SciPy function hamming() of the distance module returns this distance as a percentage.

Distance Calculcations Updated 15 Jul 2025 1 min read

Overview

  • Hamming distance between two one dimensional arrays of same length is given by the number of places the elements differ.
  • The Scipy function hamming() of the scipy.spatial.distance module returns this difference as a percentage to the length of an array.

Example

python
# Example Python program that computes the Hamming

            # distance between two one dimensional arrays using

            # the scipy library

            import scipy.spatial.distance as dist

            import numpy as np

# Arrays

            primes     = [2,3,5,7]

            odds       = [1,3,5,7]

# Compute the Hamming distance

            hammingDist = dist.hamming(primes, odds)

            print("Hamming distance:%.4f"%hammingDist)

Output

Output
Hamming distance:0.2500