-1

I've been trying to add 2 matrices by using 2 for loops but I keep getting the error: 'int' object is not iterable in the line for i in len(B):. What am I doing wrong?

def add (A,B):
    for i in len(B):
        for j in len(A):
            A[j][i] += B[i]
    return A

A = [[2, 8], [3, 7], [4, 5]]
B = [1, 2]
A = add(A,B)
print(C)

2 Answers2

0

len(b) produces an int. You can't iterate over an int.. To generate a sequence of ints upto len(b) use range.

def add (A,B):
    for i in range(len(B)):
        for j in range(len(A)):
            A[j][i] += B[i]
    return A

A = [[2, 8], [3, 7], [4, 5]]
B = [1, 2]
A = add(A,B)
print(C)
palivek
  • 115
  • 7
Jay Shankar Gupta
  • 5,918
  • 1
  • 10
  • 27
0

You need an iterable object to iterate over in the for loop. len() returns an int which is not iterable.

See this post.

Try using range() instead like

for i in range(len(B)):
    for j in range(len(A)):
        A[j][i] += B[i]
J...S
  • 5,079
  • 1
  • 20
  • 35