Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly convert list of one element to a tuple with one element

>>> list=['Hello']
>>> tuple(list)
('Hello',)

Why is the result of the above statements ('Hello',) and not ('Hello')?. I would have expected it to be the later.

like image 801
Danish Avatar asked Dec 16 '22 14:12

Danish


1 Answers

You've got it right. In python if you do:

a = ("hello")

a will be a string since the parenthesis in this context are used for grouping things together. It is actually the comma which makes a tuple, not the parenthesis (parenthesis are just needed to avoid ambiguity in certain situations like function calls)...

a = "Hello","goodbye"  #Look Ma!  No Parenthesis!
print (type(a)) #<type 'tuple'>
a = ("Hello")
print (type(a)) #<type 'str'>
a = ("Hello",)
print (type(a)) #<type 'tuple'>
a = "Hello",
print (type(a)) #<type 'tuple'>

And finally (and most direct for your question):

>>> a = ['Hello']
>>> b = tuple(a)
>>> print (type(b))  #<type 'tuple'> -- It thinks it is a tuple
>>> print (b[0])  #'Hello' -- It acts like a tuple too -- Must be :)
like image 123
mgilson Avatar answered Dec 21 '22 09:12

mgilson