A new to Python question

Bengt Richter bokr at oz.net
Sun May 15 04:45:20 EDT 2005


On Sun, 15 May 2005 08:00:47 +0200, "Fredrik Lundh" <fredrik at pythonware.com> wrote:

>M.E.Farmer wrote:
>
>> I said exactly what I meant, the parentheses around the values creates
>> a tuple that you have no reference to!
>
>repeating it doesn't make you right; no extra tuple is created, and the
>parens are part of the syntax:
>
>    If the target is a target list enclosed in parentheses or in square
>    brackets: The object must be a sequence with the same number
>    of items as there are targets in the target list, and its items are
>    assigned, from left to right, to the corresponding targets.
>
>    http://docs.python.org/ref/assignment.html
>
>(originally, you had to use [] to unpack lists, and () or no parens only
>worked for tuples.  the ability to use an arbitrary sequence was added
>in 1.5)
>
Note that (x) without a comma doesn't unpack like [x] however:

 >>> (x)= 123,
 >>> x
 (123,)
 >>> [x]= 123,
 >>> x
 123
 >>> (x,)= 123,
 >>> x
 123
 >>> x,= 123,
 >>> x
 123

Also, BTW,

 >>> 123,
 (123,)
 >>> [123,]
 [123]

I.e., that last result is not [(123,)]

There's actually a bunch of context-sensitive things about commas that
you just have to get used to, in lists, tuples, function call arg lists,
subscripts (__getitem__ args), unpacking assignment targets, etc.

>on the other hand, the function you're calling in this example *does*
>create a tuple that you have no reference to after the assignment.
Yeah, but it would create that tuple whether there was an assignment
of the returned result or not. Collecting unconnected facts in one
breath remind me too much of political speeches ;-)
>that doesn't matter, of course, since the tuple is removed by the
>garbage collector immediately after it has been unpacked.
I'm too tired to figure a humorous segue ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list