[Tutor] Unexpected iterator
Alan Plum
alan.plum at uni-koeln.de
Sun Nov 15 16:52:06 CET 2009
On So, 2009-11-15 at 15:12 +0000, Stephen Nelson-Smith wrote:
> > To upack your variables a and b you need an iterable object on the right
> > side, which returns you exactly 2 variables
>
> What does 'unpack' mean? I've seen a few Python errors about packing
> and unpacking. What does it mean?
Unpacking refers to taking a collection of values and assigning it to a
collection of variables.
(a,b) = (1,2,3) # this won't work
Let's see what it actually means (in pseudo-code):
(a,b)[0] = (1,2,3)[0] # a = 1
(a,b)[1] = (1,2,3)[1] # b = 2
(a,b)[2] = (1,2,3)[2] # undefined! = 3
Same goes for the inverse:
(a,b,c) = (1,2) # this won't work either
in pseudo code:
(a,b,c)[0] = (1,2)[0] # a = 1
(a,b,c)[1] = (1,2)[1] # b = 2
(a,b,c)[2] = (1,2)[2] # c = undefined!
Basically, just make sure your len(variables) == len(values) before
trying to use the unpacking syntax:
(a,b,c) = (1,2,3) # this works
(a,b) = (1,2) # this works, too
Cheers
Alan
More information about the Tutor
mailing list