How to Compute the Dot Product of Vectors in Python

How to Compute the Dot Product of Vectors in Python

The dot product multiplies corresponding components of two vectors and sums the results.

One critical condition for calculating the dot product is that both vectors must have the same number of components, meaning they must be of equal dimension. The dot product is also known as the scalar product because the operation returns a single number. 

For example, consider two vectors a and :

  • Vector a = [2, 5]
  • Vector b = [3, 6]

The dot product of a and is calculated as follows:

  1. Multiply the first component of a by the first component of b:
    • 2 × 3 = 6
  2. Multiply the second component of a by the second component of b:
    • 5 × 6 = 30
  3. Add these products together:
    • 6 + 30 = 36

Thus, the dot product of a and is 36

Now that we’ve seen how to manually calculate the dot product, let’s implement it in Python:

import numpy as np

# Define two vectors
Vector_a = np.array([2, 5])
Vector_b = np.array([3, 6])

# Compute the dot product using numpy
dot_product =, Vector_b)

print("Dot Product of Vector_a and Vector_b:", dot_product)

This code snippet will output:

Dot Product of Vector_a and Vector_b: 36

The dot product of two vectors is commutative, which means that the order in which the vectors are multiplied does not change the result. For instance, the dot product of vector a with vector b is the same as the dot product of vector b with vector a:

# Compute dot product from b to a
dot_product_ba =, Vector_a)

print("Dot Product of Vector_b and Vector_a:", dot_product_ba)

This code will confirm that the dot product is commutative:

Dot Product of Vector_b and Vector_a: 36

When attempting to compute the dot product of vectors with different dimensions, an error occurs because each component of one vector must correspond to a component in the other. Let’s see what happens when we try this with vectors of different sizes:

# Define a new vector with a different dimension
Vector_c = np.array([1, 2, 3])

    # Attempt to compute the dot product of Vector_a and Vector_c
    dot_product_ac =, Vector_c)
except ValueError as e:
    print("Error:", e)

This will result in the following output:

Error: shapes (2,) and (3,) not aligned: 2 (dim 0) != 3 (dim 0)

This error message from numpy clearly states that the dimensions of the vectors do not align, highlighting the necessity of having vectors of equal dimensions to compute their dot product. 

With a clear understanding of how to compute the dot product in Python, we unlock new ways to analyze and manipulate vectors. 

Leave a Reply

Your email address will not be published. Required fields are marked *