Question about tuple lengths

MM Zeeman mmzeeman at xs4all.nl
Wed Dec 14 20:57:14 CET 2005


Carl J. Van Arsdall wrote:

> 
>  From my interpreter prompt:
> 
>  >>> tuple = ("blah")
>  >>> len(tuple)
> 4
>  >>> tuple2 = ("blah",)
>  >>> len (tuple2)
> 1
> 
> So why is a tuple containing the string "blah" without the comma of
> length four? Is there a good reason for this or is this a bug?
> 

Hello,

Thats because the expression ("blah") actually resolves to "blah" instead of
a tuple containing the string "blah".

>>> type(("spam"))
<type 'str'>

Adding a comma after spam results in the tuple being created.

>>> type(("spam",))
<type 'tuple'>

And to make things even more confusing, just adding a comma without braces
will give you a tuple too.

>>> "spam",
('spam',)

The explanation for this all can be found at:
http://docs.python.org/ref/parenthesized.html

Regards,

Maas





More information about the Python-list mailing list