How to create a "singleton" tuple with only one element

Question:

In the below example I would expect all the elements to be tuples, why is a tuple converted to a string when it only contains a single string?

>>> a = [('a'), ('b'), ('c', 'd')]
>>> a
['a', 'b', ('c', 'd')]
>>> 
>>> for elem in a:
...     print type(elem)
... 
<type 'str'>
<type 'str'>
<type 'tuple'>
Asked By: Russell

||

Answers:

Your first two examples are not tuples, they are strings. Single-item tuples require a trailing comma, as in:

>>> a = [('a',), ('b',), ('c', 'd')]
>>> a
[('a',), ('b',), ('c', 'd')]
Answered By: Frédéric Hamidi

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'])
Answered By: Jonathon Reinhart

('a') is not a tuple, but just a string.

You need to add an extra comma at the end to make python take them as tuple: –

>>> a = [('a',), ('b',), ('c', 'd')]
>>> a
[('a',), ('b',), ('c', 'd')]
>>> 
Answered By: Rohit Jain

Came across this page and I was surprised why no one mentioned one of the pretty common method for tuple with one element. May be this is version thing since this is a very old post. Anyway here it is:

>>> b = tuple(('a'))
>>> type(b)
<class 'tuple'>
Answered By: Aaj Kaal

=> If you need to convert list to tuple which have one id as a element. then this solution will help you.

x_list = [1]

x_tuple = tuple(x_list)

=> You will get this

(1,)

=> so now append 0 into list and then convert it into tuple

=> x_list.append(0)

=> x_tuple = tuple(x_list)

(1, 0)
Answered By: Jaydip Solanki
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.