why does this unpacking work

Jon Clements joncle at googlemail.com
Fri Oct 20 21:44:58 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.
>
> What seems to be happening is that 'for x,y in t' is acting like:
>
> for x in t:
>      for y,z in x:
>          #then it does it correctly
>
> But if so, why is this? It doesn't seem like very intuitive behavior.

It makes perfect sense: in fact, you have kind of explained it
yourself!

Think of the for statement as returning the next element of some
sequence; in this case it's a tuple. Then on the left side, the
unpacking occurs. Using "for x in t", means that effectively no
unpackig occurs, so you get the tuple. However, since the in is
returning a tuple, using "for x,y in t", the tuple returned gets
unpacked.

Hope that helps.

Jon.




More information about the Python-list mailing list