0

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)
8
  • 1
    The loop runs twice, once with x = a and then x = 6, thus callingprint(a+b) twice. Commented Jun 20, 2020 at 18:45
  • 1
    Okay; what is your question? Commented Jun 20, 2020 at 18:45
  • Hello and welcome to StackOverflow! It's not clear what you're trying to do. Do you want to merely add a and b coordinate-wise? If so, you can just do a+b. You don't need a for loop. Commented Jun 20, 2020 at 18:45
  • Hi @Daniel Yes, It was a task given to me to add arrays in a for loop. Commented Jun 20, 2020 at 19:01
  • @KarlKnechtel i want the ouptut to be executed once not twice. Commented Jun 20, 2020 at 19:03

3 Answers 3

3

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]
Sign up to request clarification or add additional context in comments.

6 Comments

Hi @Nathan Thomas I need to add them using for loop so i tried in that way but output i got is [1 2 3 4 5 6] [ 8 10 12 5 7 9] [ 8 10 12 5 7 9]
What do you mean by you need to add them using a for loop?
I need to add two arrays using for loop so i executed that code but the output was printed twice though i have mentioned the range.
Why do you need to use a for loop?
So the answer I provided is probably the best way to do it. Using a for loop isn't best practice for this kind of operation, you could say that this answer is more "pythonic" than a for loop. But if your task states that you MUST use a for loop, try: [i+j for i,j in zip(a,b)]
|
2

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)

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.