why does this unpacking work

Carsten Haese carsten at uniqsys.com
Fri Oct 20 21:37:40 CEST 2006

On Fri, 2006-10-20 at 15:14, 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. 

t doesn't "return" anything, t *is* a nested tuple.

> Then 'for x in t' returns the nested tuples themselves.

It again doesn't "return" anything. It assigns each element of tuple t
to x, one by one, executing the loop body for each element.

> 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.

You're thinking of "x,y = 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

No, it's actually behaving like

for x in t:
  y,z = t
  # do something with y and z

You seem to have difficulty distinguishing the concept of looping over a
tuple from the concept of unpacking a tuple. This difficulty is
compounded by the fact that, in your example above, you are looping over
a tuple of tuples and unpacking each inner tuple on the fly.

Hope this helps,


More information about the Python-list mailing list