Home > Software engineering >  "'NoneType' object is not subscriptable" error
"'NoneType' object is not subscriptable" error

Time:05-06

I am new to python and I have a problem with this code. I dont understand why I can not run the code: print(m[1][1])

I always get this error message: TypeError: 'NoneType' object is not subscriptable

    edges = [(1,2), (2,7), (1,3), (2,4), (4,7), (3,5), (4,5), (5,6), (6,7), (1,8), (5,8), (6,9), (7,9), (9,10), (5,10), (8,10)]`

    def generateAdjMatrix(edges):
    
        max_knoten = max(max(edges))
        
        matrix = [[0 for i in range(max_knoten)] for j in range(max_knoten)]
        
        for kante in edges:
            matrix[kante[0]-1][kante[1]-1] = 1
    pass
    
    if __name__ == '__main__':
        m = generateAdjMatrix(edges)
        print(m[1][1])
    
    pass

CodePudding user response:

m is None after m = generateAdjMatrix(edges) because generateAdjMatrix doesn't explicitly return anything.

See Defining Functions in the documentation:

Coming from other languages, you might object that fib is not a function but a procedure since it doesn’t return a value. In fact, even functions without a return statement do return a value, albeit a rather boring one. This value is called None (it’s a built-in name).

CodePudding user response:

m = generateAdjMatrix(edges)

You are calling this function, and this function was declared with this body:

max_knoten = max(max(edges))
    
matrix = [[0 for i in range(max_knoten)] for j in range(max_knoten)]
    
for kante in edges:
    matrix[kante[0]-1][kante[1]-1] = 1

Do you see any return? No, because your function is the equivalent to a C/C void function.

So what is being put into m? Nothing, which in Python is None, an object of type NoneType.


In general, while programming in Python, if you get an error message like this:

TypeError: 'NoneType' object is not subscriptable

you have to check where does the variable you are subscripting come from.

  • Related