TypeError: ‘list’ object is not callable

TypeError: ‘list’ object is not callable

This tutorial guides you on how to resolve error TypeError: ‘list’ object is not callable in Python programming while executing code that split the given list in to equal size of chunks n.

TypeError: ‘list’ object is not callable

TypeError: ‘list’ object is not callable

For example, the given input list is as follows.

mylist = ['apple', 'boy', 'cat', 'dog', 'elephant', 'frog', 'goat', 'hen', 'ink', 'jug', 'kite', 'lion']

Below is the function that is required to split the given list in to chunks for size n.

def split_chunks(li,n):
    for i in range(0, len(li), n):
        yield li[i:i + n]

The output shows the error TypeError: ‘list’ object is not callable while creating list of chunks that is split using the function defined.

n=3
chunks = list(split_chunks(mylist,n))

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-17-451a37ad4340> in <module>
----> 1 chunks = list(split_chunks(mylist,n))

TypeError: 'list' object is not callable

In the above code everything looks fine syntactically. Then what could be the problem ?

In the next section let’s understand what could be the reason for this TypeError. Also, let’s learn how to solve the error.

Solution

The reason for the above error is Python looks for a “list” and finds it in the global namespace, but it is not the proper “list” i.e., somewhere I would have assigned an actual list instance to the name list and it shadowed the built-in list. Hence we get this TypeError.

Therefore, to resolve the above error I need to delete the name list from global namespace.

Let’s remove “list” from global namespace by running the following del list command.

del list

Therefore, it is recommended to use Python IDE like PyCharm or anyother IDE that you like, so that it highlights the name shadowing to avoid any such errors.

After removing the name “list” from namespace try running the following code to check the output.

n=3
chunks = list(split_chunks(my_list,n))
print(chunks)

[['apple', 'boy', 'cat'], ['dog', 'elephant', 'frog'], ['goat', 'hen', 'ink'], ['jug', 'kite', 'lion']]

Yay! it works. You could see the given list is split in to size of chunks n. Hence the issue is resolved.

Hope this is helpful 🙂

You’ll also like:

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments