why does this unpacking work
John Salerno
johnjsal at NOSPAMgmail.com
Fri Oct 20 15:14:56 EDT 2006
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.
Thanks.
More information about the Python-list
mailing list