Convert list to tuple in Python
I'm trying to convert a list to a tuple.
When I google it, I find a lot of answers similar to:
l = [4,5,6]
tuple(l)
But if I do that I get this error message:
TypeError: 'tuple' object is not callable
How can I fix this problem?
It should work fine. Don't use tuple
, list
or other special names as a variable name. It's probably what's causing your problem.
>>> l = [4,5,6]
>>> tuple(l)
(4, 5, 6)
Expanding on eumiro's comment, normally tuple(l)
will convert a list l
into a tuple:
In [1]: l = [4,5,6]
In [2]: tuple
Out[2]: <type 'tuple'>
In [3]: tuple(l)
Out[3]: (4, 5, 6)
However, if you've redefined tuple
to be a tuple rather than the type
tuple
:
In [4]: tuple = tuple(l)
In [5]: tuple
Out[5]: (4, 5, 6)
then you get a TypeError since the tuple itself is not callable:
In [6]: tuple(l)
TypeError: 'tuple' object is not callable
You can recover the original definition for tuple
by quitting and restarting your interpreter, or (thanks to @glglgl):
In [6]: del tuple
In [7]: tuple
Out[7]: <type 'tuple'>
You might have done something like this:
>>> tuple = 45, 34 # You used `tuple` as a variable here
>>> tuple
(45, 34)
>>> l = [4, 5, 6]
>>> tuple(l) # Will try to invoke the variable `tuple` rather than tuple type.
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
tuple(l)
TypeError: 'tuple' object is not callable
>>>
>>> del tuple # You can delete the object tuple created earlier to make it work
>>> tuple(l)
(4, 5, 6)
Here's the problem... Since you have used a tuple
variable to hold a tuple (45, 34)
earlier... So, now tuple
is an object
of type tuple
now...
It is no more a type
and hence, it is no more Callable
.
Never
use any built-in types as your variable name... You do have any other name to use. Use any arbitrary name for your variable instead...
上一篇: 列表中是否有一个简短的包含函数?
下一篇: 在Python中将列表转换为元组