default tuple unpacking?

Peter Hansen peter at engcorp.com
Thu Sep 5 04:37:05 CEST 2002


Bernhard Herzog wrote:
> Peter Hansen <peter at engcorp.com> writes:
> 
> 
>>Hmm... I think there might be an inconsistency or an unexpected
>>result in this.  What if e already contains a tuple?
>>
>>   e = (1, 2, 3)
>>   *a = e        # a is ((1, 2, 3), )
>>
>>That seems sensible, and it's just what happens if you pass
>>"e" in to a function defined as "def func(*a)".
> 
> No it isn't. If you call func as func(e) the tuple being unpacked into
> the function's parameters is (e,) not e. So the situation is more like
> calling func as func(*e) so that *a = e would be the same as a = e or
> perhaps a = tuple(e)

Quite right... my mistake.

>>Now what about this:
>>
>>   a, *b = e     # a is 1, b is (2, 3)
>>
>>That's one possible result, and presumably the one you want with
>>this syntax, but it's not what you'd get with the function syntax:
>>
>>   def func(a, *b):
>>     print a
>>     print b
>>
>>   func(e)
> 
> 
> Again the tuple being upacked to a, *b is (e,)...
> 
>>Here of course you get (1, 2, 3) in "a" and () in b. 
> 
> ... so this is obviously what you should get.

A sign that even when one can use these effectively in programs, one
can be confused by the arbitrary choice of syntax when talking about
it.  Thanks for the corrections.

-Peter




More information about the Python-list mailing list