How to compute outer product using Python

An outer product, also known as a vector matrix product, is a kind of vector multiplication that outputs a matrix. Suppose we have two column vectors X Xand YYof dimensions m×1m \times 1 and n×1 n \times 1 respectively.

The outer product of these vectors will be a matrix MMof shape m×nm \times n.

The outer product is represented by the symbol \otimes. Taking the outer product of two vectors is equivalent to multiplying the first vector with the transpose of the second.

The first element of the column vector XX will multiply with all the elements of row vector YY, then the second element of column vector XX will multiply with all the elements of row vector YY, and so on until the entire m×nm \times n matrix has been populated.

First element of x with the first element of y
First element of x with the first element of y
1 of 8

How to calculate the outer product in Python?

To calculate the outer product of two vectors in Python, we can use a function provided by the NumPy library named outer(). To check how it works, let's consider the following two simple column vectors.

The outer product of the two will be:

The code below shows how this outer product can be calculated using the outer() function.

import numpy as np
a = [1, 2, 3, 4]
b = [8, 7, 6, 5]
outer_product = np.outer(a, b)
print(outer_product)

Code explanation

  • Line 1: Import the numpy library.

  • Lines 3–4: Define two lists that will be treated as vectors.

  • Line 6: Call NumPy’s outer() function to calculate the outer product of the two vectors.

  • Line 8: Display the computed matrix on the screen.

Knowledge test

Let's try the following quiz to test our understanding.

Quiz

Q

What will be ABA\otimes B for the following vectors? A=[123],  B=[456]A = \begin{bmatrix} 1 \\ 2 \\ 3 \\\end{bmatrix}, \ \ B = \begin{bmatrix} 4 \\ 5 \\ 6 \end{bmatrix}

A)

[48125101561218]\begin{bmatrix} 4 & 8 & 12 \\ 5 & 10 & 15 \\ 6 & 12 & 18 \end{bmatrix}

B)

[41018]\begin{bmatrix} 4 \\ 10\\ 18 \end{bmatrix}

C)

[45681012121518]\begin{bmatrix} 4 & 5 & 6 \\ 8 & 10 & 12 \\ 12 & 15 & 18 \end{bmatrix}

D)

[65412108181512]\begin{bmatrix} 6 & 5 & 4 \\ 12 & 10 & 8 \\ 18 & 15 & 12 \end{bmatrix}

Conclusion

By employing the numpy.outer() function, users can compute the outer product of two vectors, facilitating various applications in mathematics, statistics, and data analysis. Through this article, we have explored the concept of the outer product, its mathematical representation, and its implementation in Python using NumPy, providing readers with a comprehensive understanding of this fundamental operation.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved