TypeError: the 'int' object is not subscript (python)


I'm having problems making a matrix multiplication algorithm in python3.

This is the code:

def matrixMult(m1, m2):
    result = [[0 for x in range(len(m1))] for x in range(len(m2[0]))]
    # Iterate through rows of m1.
    for i in range(len(m1)):
        # Iterate through columns of m2.
        for j in range(len(m2[0])):
            # Iterate through rows of m2.
            for k in range(len(m2)):
                result[i][j] += m1[i][k] * m2[k][j]   # error occurs here.

    return result

Trying to call it on two random matrices like so:

m = [3, 4, 2]
n = [[13, 9, 7, 15], [8, 7, 4, 6], [6, 4, 0, 3]]
r = matrixMult(m, n)

This results in the TypeError: 'int' object is not subscriptable message.

I added a print(type()) for both the matrices declared above and they are of class 'list'. Did the same for the classes used in the function prototype, class 'list'. Hell, everything is of type 'list'. I don't know what the int object is.

You are treating m1 as a nested list of integers:

result[i][j] += m1[i][k] * m2[k][j]
#               ^^^^^^^^

It is not; it is merely a simple list of integers. m1[i] then is an integer object and you cannot index integers:

>>> [3, 4, 2][0]
>>> [3, 4, 2][0][0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object has no attribute '__getitem__'

You probably want to use just i as the index:

result[i][j] += m1[i] * m2[k][j]

or pass in two-dimensional arrays only (so pass in [[3], [4], [2]] rather than [3, 4, 2]).