Why does () create an empty tuple in Python?
Asked Answered
M

3

6
>>> x = ()
>>> type(x)
tuple

I've always thought of , as the tuple literal 'constructor,' because, in every other situation, creating a tuple literal requires a comma, (and parentheses seem to be almost superfluous, except perhaps for readability):

>>> y = (1)
>>> type(y)
int

>>> z = (1,)
>>> type(z)
tuple

>>> a = 1,
>>> type(a)
tuple

Why is () the exception? Based on the above, it seems to make more sense for it to return None. In fact:

>>> b = (None)
>>> type(b)
NoneType
Marmot answered 5/3, 2022 at 3:51 Comment(1)
I consider the 1 element case, ("x",) to be the only special one. It is of course necessary to differentiate between a tuple declaration and an expression wrapped in parentheses. Other than the 1 element case, tuples are created by separating their elements with commas. Since for the zero element case, there are no elements, there's nothing to separate. I've always considered the parentheses to be the key part of the construction.Lazy
D
4

The Python documentation knows that this is counter-intuitive, so it quotes:

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. For example:

>> empty = ()
>> singleton = 'hello',    # <-- note trailing comma
>> len(empty)
0
>> len(singleton)
1
>> singleton
('hello',)

See Tuples and Sequences for more info and for the quote above.

Demodulator answered 5/3, 2022 at 4:3 Comment(0)
S
1

According to Python 3 Documentation:

Tuples may be constructed in a number of ways:

  • Using a pair of parentheses to denote the empty tuple: ()
  • Using a trailing comma for a singleton tuple: a, or (a,)
  • Separating items with commas: a, b, c or (a, b, c)
  • Using the tuple() built-in: tuple() or tuple(iterable)
Spatterdash answered 5/3, 2022 at 3:57 Comment(0)
T
0

I'd assume it is because we want to be able to construct empty tuples, and (,) is invalid syntax. Basically, somewhere it was decided that a comma requires at least one element. The special cases for 0 and 1 element tuples are noted in the docs: https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences.

Thora answered 5/3, 2022 at 3:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.