Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
numpy
add
array

How to add one array to another array in Python

Educative Answers Team

In Python, it’s easy to add one array to another with the built-in Python library NumPy. NumPy is a free Python library equipped with a collection of complex mathematical operations suitable for processing statistical data.

svg viewer

Library

NumPy can be imported into Python as follows:

import numpy as np

Method

To add the two arrays together, we will use the numpy.add(arr1,arr2) method. In order to use this method, you have to make sure that the two arrays have the same length.

If the lengths of the two arrays are​ not the same, then broadcast the size of the shorter array by adding zero’s at extra indexes.

Code

Two arrays are added using the np.add() method in the code below.

import numpy as np
 
arr1 = np.array([3, 2, 1])
arr2 = np.array([1, 2, 3])
   
print ("1st array : ", arr1)  
print ("2nd array : ", arr2)  
   
out_arr = np.add(arr1, arr2)  
print ("added array : ", out_arr)  

RELATED TAGS

python
numpy
add
array
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring