Python throws the error, ‘function’ object is not subscriptable, when we try to index or subscript a python function. Only iterables like array, list, tuples, dictionaries etc. are allowed to be indexed.
Consider this example –
def iAmAFunction(): return ["Captain America", "Hulk", "Thor"] print(iAmAFunction[1]) # Error: 'function' object is not subscriptable
The above code will throw the error because we are trying to subscript a function iAmAFunction[1]
. Although this function is returning a list, but we cannot directly subscript it. But, we can subscript the returned result. So, below form is completely valid –
iAmAFunction()[1]
Other situation where you might get this error is when you mistakenly use some function name same as one of your list name. Then, when you try to subscript your list, Python may throw function not subscriptable error. For example –
myList = ["Ironman", "Thor", "Hulk"] def myList(ind): return myList[ind] print(myList(1)) print(myList[1]) # Error
This code is wrong at multiple places because of same list and function name. Since myList
is defined as function afterwards so, it has became a function and lost its list properties. In the function, we are trying to index the myList
as myList[ind]
which is wrong now. Similarly, we can’t index it in print(myList[1])
.