7
>>> 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
1
  • 2
    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. Commented Mar 5, 2022 at 4:00

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.