[Solved] – Python – Convert list to tuple in Python
It ought to work fine. do not use tuple, list or different special names as a variable name. It’s most likely what is inflicting your drawback.
>>> l = [4,5,6] >>> tuple(l) (4, 5, 6)
Expanding on eumiro’s comment, usually tuple(l) can convert an inventory 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)
In [6]: tuple(l) TypeError: 'tuple' object is not callable
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 matter… Since you have got used a tuple variable to carry a tuple (45, 34) earlier… So, currently tuple is Associate in Nursing object of sort tuple currently…
It is no additional a sort and thus, it’s no additional due .
Never use any constitutional sorts as your variable name… you are doing have the other name to use. Use any impulsive name for your variable instead…
Example code,
#Convert list to tuple listx = [5, 10, 7, 4, 15, 3] print(listx) #use the tuple() function built-in Python, passing as parameter the list tuplex = tuple(listx) print(tuplex)
Here is your sample code,
# Python code to convert into dictionary def Convert(tup, di): for a, b in tup: di.setdefault(a, []).append(b) return di # Driver Code tups = [("akash", 10), ("gaurav", 12), ("anand", 14), ("suraj", 20), ("akhil", 25), ("ashish", 30)] dictionary = {} print (Convert(tups, dictionary))