user13782591
user13782591

Reputation:

adding two arrays in python using for loop

In the output i can view two outputs were printed

from numpy import *
a=array([1,2,3,4,5,6])
print(a)
b=array([7,8,9,1,2,3])
for x in (a,6):
    print(a+b)

Upvotes: 0

Views: 3877

Answers (3)

Arjun Kumar
Arjun Kumar

Reputation: 173

Hope this helps you

from numpy import *
a=array([1,2,3,4,5,6])
print('Value of a is: ',a)
b=array([7,8,9,1,2,3])
print('Value of b is: ',b)
c=[]

for x in range(len(a)):
    #print (a[x]+b[x])
    c.append(a[x]+b[x])

print('The sum of a+b is: ',c)

Upvotes: 2

doubleo
doubleo

Reputation: 4759

Also ensure to check the length of the two arrays, else you will run into ValueError.

from numpy import *
a=array([1,2,3,4,5])
print(a)
b=array([7,8,9,1,2])
print(b)

len_a = len(a)
len_b = len(b)
if len_a == len_b:
    print(a+b)
else:
    print("length of array_a = %d, len of array_b = %d, cannot add two arrays") % (len_a, len_b)

Upvotes: 1

Nathan Thomas
Nathan Thomas

Reputation: 270

You don't need the for loop, just do it like this:

a=np.array([1,2,3,4,5,6])
b=np.array([7,8,9,1,2,3])
print(a+b)

#Output
[ 8 10 12  5  7  9]

Upvotes: 3

Related Questions