why does this unpacking work
gagsl-py at yahoo.com.ar
Fri Oct 20 22:18:17 CEST 2006
At Friday 20/10/2006 16: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'))
>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.
You can think of
for x in t:
as meaning "for each element contained in t, name it x and do whatever"
The other concept involved is unpacking:
>>> w = (1,2,3)
>>> x,y,z = w
When you say "for x,y in t:" there is an implicit unpacking, it means
"for each element contained in t, unpack it into x and y and do whatever"
>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 acts like:
for w in t:
x,y = w
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
More information about the Python-list