Addition of Two Arrays in Python

In this post, we will see how to add two arrays in Python with some basic and interesting examples. We already know that to convert any list or number into Python array, we use NumPy. Thus, firstly we need to import the NumPy library.

We can perform the addition of two arrays in 2 different ways. We can either use the ‘+’ operator or the numpy.add( ) method. I will show you how to perform addition using both methods.

Using the ‘+’ Operator: Add two arrays

In this method, we declare two different arrays and then add them by using ‘+’ operator(addition operator) in between them. It is the same as adding two values.  The arrays act as operands and ‘+’ is the operator.

Syntax:
#let arr1 and arr2 be arrays
res = arr1 + arr2

Let’s move to some examples to verify the same.

#Python program to show addition of 2 arrays using + operator
import numpy as np

#define 2 different arrays
arr1 = np.array([1,2,3,4])
arr2 = np.array([1,2,3,4])

res = arr1 + arr2

res
Output:
array([2, 4, 6, 8])

Using The numpy.add( ) Method to add two arrays

The add( ) method is a special method that is included in the NumPy library of Python and is used to add two different arrays. We simply pass in the two arrays as arguments inside the add( ). It basically adds arguments element-wise. Syntax of the add( ) method is as shown:

Syntax:
np.add(*args, **kwargs)

Let’s jump to some examples to understand the working of this method.

 

#Python program to illustrate use of add()
import numpy as np

arr1 = np.array([1,2,3,4])
arr2 = np.array([1,2,3,4])

np.add(arr1,arr2)
Output:
array([2, 4, 6, 8])
import numpy as np

a1 = np.arange(25).reshape((5,5))
a2 = np.arange(5)

np.add(a1, a2)
Output:
array([[ 0,  2,  4,  6,  8],
       [ 5,  7,  9, 11, 13],
       [10, 12, 14, 16, 18],
       [15, 17, 19, 21, 23],
       [20, 22, 24, 26, 28]])

 

import numpy as np

a3 = np.array([[1,2,3],[1,2,3],[1,2,3]])
a4 = np.array([[1,1,1],[0,0,0],[1,1,1]])

np.add(a3,a4)
Output:
array([[2, 3, 4],
       [1, 2, 3],
       [2, 3, 4]])

NOTE: For this type of array addition, the shape of both the arrays must be the same. Or if the shape of the two arrays is not the same, they must be broadcastable to a common shape.

Also read:

Leave a Reply

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