SoFunction
Updated on 2024-11-20

Python "TypeError: 'list' object is not callable" problem and solution

concern

Error when creating a new list with the list() function

“TypeError: ‘list’ object is not callable”

rationale

At first I couldn't find the reason because my code was exactly the same as the example in the book, so why was it reporting an error?

Later onA * Q&A I found out why.Because the previous code used list for naming

I've defined a list before withlist=[1,2,3] , then felt bad about it and deleted it after running the line of code.

But Jupyter Notebook is an interactive editor, and unless the kernel is restarted, once named, the variable takes up memory.

So, the list() function is called later to run the codelist1=list(range(10)) When it does, the compiler takes one of thelist Interpreted as the previously defined list [1,2,3], the program runs with an error.

cure

1. Don't use Python datatype names such as list, tuple, etc. to name objects. Similarly, don't use the for, in keywords.

2. At this point you can usedel list In this case, the list() function will be interpreted correctly when it is used again, as it frees the memory occupied by the variable list. Also note that the previously defined list no longer exists. If you encounter a situation similar to mine in the Jupyter Notebook, you can also restart the kernel (which also frees memory) and then run the code unit where the list() function is located.

footnote

In the above * answer, the god also mentions a situation where, for example, a list is defined:nums=[1,2,3] , normally, we have to use thenums[i] to index the element.

And if you usenums(i) , it will also report the same error: "TypeError: 'list' object is not callable".

Reference:

/questions/31087111/typeerror-list-object-is-not-callable-in-python

summarize

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.