Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does () create an empty tuple in Python?

Tags:

python

tuples

>>> 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
like image 463
thariqfahry Avatar asked Aug 08 '26 08:08

thariqfahry


1 Answers

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.

like image 175
Ann Zen Avatar answered Aug 10 '26 09:08

Ann Zen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!