Reputation: 65
I got so frustrated because of this error message here and couldn't figure out what went wrong with such a simple code:
secret_word_list = list('trang')
TypeError: 'tuple' object is not callable
secret_word_list
is a new variable. where does the 'tuple' type come from? Also if I assign the string to a variable, can I cast it to a string just by calling its name. For example:
string = 'abc'
list = list(string)
I tried but the same error message kept popping up.
Also, I write this in Spyder. If I wrote in PythonTutor, things would go well.
Thank you in advance for your time!
Upvotes: 2
Views: 379
Reputation: 16720
Here's what it does when I run your code in a fresh interpreter:
>>> secret_word_list = list('trang')
>>> secret_word_list
['t', 'r', 'a', 'n', 'g']
>>>
In other words, it behaves as expected. If you take a closer look at the error you get, you can understand that Python sees that a tuple is being called:
TypeError: 'tuple' object is not callable
The only call is on list
.
Therefore, list
is a tuple.
This can only mean that list
has been rebound somewhere in your code.
You need to find the line where you wrote something like
list = ...
and use a different name instead of list
.
Upvotes: 1
Reputation: 5029
The problem is being caused because you're shadowing a builtin keyword of Python: list
.
Never create variables with names of builtin keywords.
Your code works perfectly fine if you choose another variable name:
>> string = 'abc'
>> my_list = list(string)
>> print(my_list)
['a', 'b', 'c']
I suspect you're getting a TypeError
because you previously assigned a tuple to a variable called list
.
Upvotes: 1