The typeerror: function object is not subscriptable error generates because of using indexes while invoking functional object. Generally, Functions are callable object but not subscriptible. In this article, we will see the best ways to fix this error. We will also try to understand the situations where usually this error occurs. So Lets go !!
Lets practically understand the context for this error.
def print_name(name):
print(name)
return name + " Data Science Learner "
var=print_name[0]
Here print_name is callable function. But we are not invoking it as function with parameter. IN the place of it we used index print_name[0]. Hence when we run this code , we get function object is not subscriptable python error.
The fix for this error is simple to avoid calling function using indexes. But you already know about it. So what next ? See lets simplify this for us with scenarios.-
This is one of the very common scenario for this error. Here we use the same name for function and iterable objects like ( list , dict, str etc) . If we declare the iterable object first and then function, so function will overwrite the iterable object type and throughs the same error.
print_name=[1,2,3]
def print_name(name):
print(name)
return name + " Data Science Learner "
var=print_name[0]
Hence we should always provide unique name to each identifiers. If we follow this best practice, we will never get this kind of error.
If any function is returning any iterable object but we are not assigning it into any local variable. Wile directly accessing it with indexes it throws the same type error. Lets see how –
To avoid this we can follow the the below way –
def fun():
data=[1,2,3]
return data
temp=fun()
var=temp[0]
print(var)
Thanks
Data Science Learner Team