I'm trying to convert a list to a tuple.
Most solutions on Google offer the following code:
l = [4,5,6] tuple(l) However, the code results in an error message when I run it:
TypeError: 'tuple' object is not callable
How can I fix this problem?
1) Using tuple() builtin function tuple () function can take any iterable as an argument and convert it into a tuple object. As you wish to convert a python list to a tuple, you can pass the entire list as a parameter within the tuple() function, and it will return the tuple data type as an output.
A simple way to convert a list of lists to a list of tuples is to start with an empty list. Then iterate over each list in the nested list in a simple for loop, convert it to a tuple using the tuple() function, and append it to the list of tuples.
Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called. But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.
To convert a tuple to list in Python, use the list() method. The list() is a built-in Python method that takes a tuple as an argument and returns the list. The list() takes sequence types and converts them to lists.
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) >>> tuple = 'whoops' # Don't do this >>> tuple(l) TypeError: 'tuple' object is not callable
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'>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With