Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list to tuple in Python

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?

like image 378
LynnH Avatar asked Oct 11 '12 09:10

LynnH


People also ask

Can we convert list to tuple in Python?

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.

How do you convert a list of lists to tuples?

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.

Can you change a list in a tuple?

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.

How do you convert a tuple to a list of tuples in Python?

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.


2 Answers

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 
like image 101
root Avatar answered Sep 28 '22 03:09

root


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'> 
like image 25
unutbu Avatar answered Sep 28 '22 03:09

unutbu