Why tuple with one item is no tuple

Roy Smith roy at panix.com
Tue Mar 15 11:25:15 EST 2005


Gregor Horvath  <g.horvath at mx.at> wrote:
>Hi,
>
> >>>type(['1'])
><type 'list'>
>
> >>>type(('1'))
><type 'str'>
>
>I wonder why ('1') is no tuple????

You need to say ('1',).  In just plain ('1'), the parens are
interpreted as grouping, not as tuple creation.  Depending on your
point of view, this is either a "special case", or an "ugly wart" in
the syntax.

a = ()       # tuple of zero elements
a = (1,)     # tuple of one element
a = 1,       # tuple of one element
a = (1)      # scalar
a = (1, 2)   # tuple of two elements
a = 1, 2     # tuple of two elements
a = ,        # syntax error

The big question is, is it the parens that make it a tuple, or is it
the comma?  If you go along with the parens school of thought, then
(1,) is the special case.  If you believe in commas, then the () is
the special case.  In either case, it's a bit ugly, but we learn to
overlook the occasional cosmetic blemishes of those we love :-)



More information about the Python-list mailing list