>>> 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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With