unpacking with default values

Gary Herron gherron at islandtraining.com
Thu Jul 17 14:23:27 EDT 2008


McA wrote:
> On 17 Jul., 18:33, Gary Herron <gher... at islandtraining.com> wrote:
>   
>> In Python 2.x, you can't do that directly, but you should be able to
>> create a function that lengthens or shortens an input tuple of arguments
>> to the correct length so you can do:
>>
>>   a,c,b = fix(1,2)
>>   d,e,f = fix(1,2,3,4)
>>
>> However, the function won't know the length of the left hand side
>> sequence, so it will have to be passed in as an extra parameter or hard
>> coded.
>>     
>
> Hi Gary,
>
> thank you for the answer.
> Do you know the "protocol" used by python while unpacking?
> Is it a direct assingnment? Or iterating?
>   

Both I think, but what do you mean by *direct* assignment?

> Best regards
> Andreas Mock
> --
> http://mail.python.org/mailman/listinfo/python-list
>   

It RHS of such an assignment can be any iterable (I think).  Lets test:
(The nice thing about an interactive Python session, it that it's really 
easy to test.)


 >>> L = [1,2,3]
 >>> a,b,c=L
 >>> a,b=L
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
 >>> a,b,c,d=L
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 3 values to unpack

 >>> G = (f for f in [1,2,3])   # A generator expression
 >>> a,b,c = G
 >>> G = (f for f in [1,2,3])   # A generator expression
 >>> a,b = G
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
 >>> G = (f for f in [1,2,3])   # A generator expression
 >>> a,b,c,d = G
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 3 values to unpack


I'd call that direct assignment with values supplied by any iterable.

Gary Herron








More information about the Python-list mailing list