Question about tuple lengths

  • Thread starter Carl J. Van Arsdall
  • Start date
C

Carl J. Van Arsdall

From my interpreter prompt:
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?

--

Carl J. Van Arsdall
(e-mail address removed)
Build and Release
MontaVista Software
 
M

MM Zeeman

Carl said:
From my interpreter prompt:

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 'str'>

Adding a comma after spam results in the tuple being created.
<type 'tuple'>

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

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

Regards,

Maas
 
S

Steven D'Aprano

From my interpreter prompt:

There is a special place in Hell reserved for people who overwrite
built-in functions like tuple(), list(), str() and so forth. *wink*


Brackets on their own are just used for grouping, so ("blah") is the same
as just "blah", namely a string with four characters.

The only exception to this is the empty tuple, which is made with an empty ().


Tuples are made with commas, not brackets. You could write just "blah",
without the brackets and it would still work.

py> t = "blah",
py> t
('blah',)

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?

It's not a bug.
 
L

Larry Bates

Carl said:
From my interpreter prompt:

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?

Additional note:

You should not give a tuple a variable name of tuple, it masks
the built-in tuple() function. This also goes for str, or other
built-ins. This will "bite" you at some point if it hasn't already.

-Larry Bates
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top