0
A = [[1,1,1,1],[1,1,1,1]]
B = [[1,1,1,1], [1,1,1,1]]
sum = []

m=len(A[0])
n=len(A)

for i in range(n):
    for j in range(m):
        sum.append(A[i][j]+B[i][j])

print(sum)

I have result [2,2,2,2,2,2,2,2], but I need [[2,2,2,2],[2,2,2,2]].

1
  • You shouldn't name your variables ,,sum'', sum is python function and if you override it you won't be able to use it. Commented Nov 18, 2018 at 12:41

2 Answers 2

1

Consider numpy.

>>> import numpy as np
>>> np.add(A, B)
array([[2, 2, 2, 2],
       [2, 2, 2, 2]])

If you don't want to use numpy, consider the following:

>>> [[sum(pair) for pair in zip(sub1, sub2)] for sub1, sub2 in zip(A, B)]
[[2, 2, 2, 2], [2, 2, 2, 2]]

Also do not use sum = [], you will reassign the built in sum function, leading to TypeError: 'list' object is not callable errors.

Sign up to request clarification or add additional context in comments.

2 Comments

I can't use numpy.
@polko does the non-numpy solution work for you, then?
0

you can do it easier but about your current code,change it like this:

for i in range(n):
    v=[]
    for j in range(m):
        v.append(A[i][j]+B[i][j])
    sum.append(v)

2 Comments

Would you like to explain me it?
Yes. in each iteration you calculate a 2 and append it to sum. but in my solution, you create a list of 2s, then append that list to sum. and in next iteration of the outer loop, you create an empty list again.@polko

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.