Calculating the Manhattan distance using SciPy

The Manhattan distance, also known as the City Block distance, is calculated as the sum of absolute differences between the two vectors. It is mostly used for the vectors that describe objects on a uniform grid such as a city block or chessboard. Below is the generalized formula to calculate Manhattan distance in n-dimensional space −

$$\mathrm{D =\sum_{i=1}^{n}|r_i-s_i|}$$


si and ri are data points.

n denotes the n-space.

SciPy provides us with a function named cityblock that returns the Manhattan Distance between two points. Let’s see how we can calculate the Manhattan distance between two points using SciPy library−


# Importing the SciPy library
from scipy.spatial import distance
# Defining the points
A = (1, 2, 3, 4, 5, 6)
B = (7, 8, 9, 10, 11, 12)
A, B

# Computing the Manhattan distance
manhattan_distance = distance.cityblock(A, B)
print('Manhattan Distance b/w', A, 'and', B, 'is: ', manhattan_distance)


Manhattan Distance b/w (1, 2, 3, 4, 5, 6) and (7, 8, 9, 10, 11, 12) is: 36