Home »
Python »
Python Programs
How to perform outer addition with NumPy?
Learn, how can we perform outer addition with Python NumPy?
By Pranit Sharma Last updated : December 26, 2023
Problem statement
Suppose that we are given a numpy array and we need to perform outer addition/multiplication using some technique rather than using a for loop.
Performing outer addition with NumPy
Many of NumPy's basic operators such as numpy.add(), numpy.subtract(), numpy.multiply(), etc. are known as universal functions (ufuncs)
In NumPy, all universal functions that take two input arguments have an attribute called outer. With the help of this attribute, all the outer entities can be used whether in addition, subtraction, or multiplication.
Let us understand with the help of an example,
Python code to perform outer addition with NumPy
# Import numpy
import numpy as np
# Creating array
arr = np.array([1, 2, 3])
# Display Original array
print("Original array:\n",arr,"\n")
# Outer addition
res = np.add.outer(arr,arr)
# Display result
print("Outer addition:\n",res,"\n")
# Outer subtraction
res = np.subtract.outer(arr,arr)
# Display result
print("Outer subtraction:\n",res,"\n")
Output
In this example, we have used the following Python basic topics that you should learn:
Python NumPy Programs »
Advertisement
Advertisement