why is a tuple converted to a string when it only contains a single string?
a = [('a'), ('b'), ('c', 'd')]
Because those first two elements aren't tuples; they're just strings. The parenthesis don't automatically make them tuples. You have to add a comma after the string to indicate to python that it should be a tuple.
>>> type( ('a') )
<type 'str'>
>>> type( ('a',) )
<type 'tuple'>
To fix your example code, add commas here:
>>> a = [('a',), ('b',), ('c', 'd')]
^ ^
From the Python Docs:
A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective.
If you truly hate the trailing comma syntax, a workaround is to pass a list
to the tuple()
function:
x = tuple(['a'])
('a')
just evaluates to'a'
– Parmesan,
:a = 1, 2, 3; print a
– Dote()
, which only consists in a pair of parentheses. – InnervateFalse
- just about all an empty tuple is good for (if you see what I mean). – Symon('a')
is taken as an expression that evaluates to'a'
. Tuples need a comma to be a tuple, except the empty tuple, which is empty parentheses,()
. – Bayardtuple
is an object delimited by comma not an object enclosed in parentheses. So a singletontuple
would be like ('a',) or tuple('a') – Hughhughes(True)
and(False)
are boolean types so that evaluating(1 == 2)
is equivalent to1 == 2
– Illeetvilaine