Computing Manhattan distance using Python

The function cityblock() computes the Manhattan distance between two points in the real co-ordinate space. The Pythone example computes the distance using the same data points

Distance Calculcations Updated 16 Jul 2025 1 min read

Overview

  • The Manhattan distance or City Block distance is computed by summing the distances in each axis of the given two points.
  • It is never the shortest distance between the two points in real co-ordinate space as it involves traversing in each direction given by the data point.
  • The Manhattan distance is greater in value than the Euclidean distance. Euclidean distance is the shortest distance between two points in real co-ordinate space.

Example

The example uses the first two points of the dataset from the hierarchical clustering using Python. The Euclidean distance between the two points is 0.05040794 whereas the Manhattan distance between the two points is 0.05639999.

python
# Example Python program that finds the

            # Manhattan distance between a set of 2-dimensional

            # data points

import scipy.spatial.distance as dist

            import numpy

# Body weights and brain weights of crow and parrot

            parrot    = [0.5,    0.01365]

            crow     = [0.45,   0.00725]

# Compute the Manhattan distance

            manhattan_distance = dist.cityblock(parrot, crow)

            print("Manhattan distance between the points:")

            print(manhattan_distance)

# Compute the Euclidean distance

            euclidean_distance = dist.euclidean(parrot, crow)

            print("Euclidean distance between the points:")

            print(euclidean_distance)

# Compare the Manhattan distance with the Euclidean distance

            result = manhattan_distance < euclidean_distance

            print("Is the Manhattan distance lesser than Euclidean distance?")

            print(result)

Output

Output
Manhattan distance between the points:

            0.05639999999999999

            Euclidean distance between the points:

            0.05040793588315236

            Is the Manhattan distance lesser than Euclidean distance?

            False