why does this unpacking work

Paddy paddy3118 at netscape.net
Sat Oct 21 04:54:46 CEST 2006


John Salerno wrote:
> I'm a little confused, but I'm sure this is something trivial. I'm
> confused about why this works:
>
>  >>> t = (('hello', 'goodbye'),
>       ('more', 'less'),
>       ('something', 'nothing'),
>       ('good', 'bad'))
>  >>> t
> (('hello', 'goodbye'), ('more', 'less'), ('something', 'nothing'),
> ('good', 'bad'))
>  >>> for x in t:
> 	print x
>
>
> ('hello', 'goodbye')
> ('more', 'less')
> ('something', 'nothing')
> ('good', 'bad')
>  >>> for x,y in t:
> 	print x,y
>
>
> hello goodbye
> more less
> something nothing
> good bad
>  >>>
>
> I understand that t returns a single tuple that contains other tuples.
> Then 'for x in t' returns the nested tuples themselves.
>
> But what I don't understand is why you can use 'for x,y in t' when t
> really only returns one thing. I see that this works, but I can't quite
> conceptualize how. I thought 'for x,y in t' would only work if t
> returned a two-tuple, which it doesn't.
>

Hi John,

Thats the point were you go astray.
iterating over t *does* produce a 2-tuple that can be unpacked
immediately.

maybe this will help, (notice that element is always one of the inner
tuples):

>>> tpl = ((00,01), (10,11), (20,21))
>>> for element in tpl:
... 	print "tpl provides this when iterated over:", element
...
tpl provides this when iterated over: (0, 1)
tpl provides this when iterated over: (10, 11)
tpl provides this when iterated over: (20, 21)
>>> for element in tpl:
... 	print "tpl provides this when iterated over:", element
... 	sub0, sub1 = element
... 	print "each element unpacks to:", sub0,"and:", sub1
...
tpl provides this when iterated over: (0, 1)
each element unpacks to: 0 and: 1
tpl provides this when iterated over: (10, 11)
each element unpacks to: 10 and: 11
tpl provides this when iterated over: (20, 21)
each element unpacks to: 20 and: 21
>>> for sub0, sub1 in tpl:
... 	print "each element of tuple unpacked immediately to:",
sub0,"and:", sub1
...
each element of tuple unpacked immediately to: 0 and: 1
each element of tuple unpacked immediately to: 10 and: 11
each element of tuple unpacked immediately to: 20 and: 21
>>> 


- Paddy.




More information about the Python-list mailing list