Home > Enterprise >  Why does () create an empty tuple in Python?
Why does () create an empty tuple in Python?

Time:03-05

>>> 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

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

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)
  • Related