Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a tuple with only one element

Tags:

python

People also ask

Can a tuple have only one element?

Tuple with one element. If the tuple contains only one element, then it's not considered as a tuple. It should have a trailing comma to specify the interpreter that it's a tuple.

What is a 1 tuple?

A 1‑tuple is called a single (or singleton), a 2‑tuple is called an ordered pair or couple, and a 3‑tuple is called a triple (or triplet). The number n can be any nonnegative integer.

How do you make a singleton tuple in Python?

A tuple of one item (a 'singleton') can be formed by affixing a comma to an expression (an expression by itself does not create a tuple, since parentheses must be usable for grouping of expressions). An empty tuple can be formed by an empty pair of parentheses.

How do you set a tuple of length 1?

How to assign a tuple of length 1 to a? A parenthesized expression list yields whatever that expression list yields: if the list contains at least one comma, it yields a tuple; otherwise, it yields the single expression that makes up the expression list.


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'])

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')]

('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')]
>>>