[Tutor] Unexpected iterator
Kent Johnson
kent37 at tds.net
Mon Nov 16 12:34:54 CET 2009
On Mon, Nov 16, 2009 at 12:17 AM, spir <denis.spir at free.fr> wrote:
> Le Sun, 15 Nov 2009 19:23:33 -0000,
> "Alan Gauld" <alan.gauld at btinternet.com> s'exprima ainsi:
>
>> What does 'unpack' mean? I've seen a few Python errors about packing
>> and unpacking. What does it mean?
>
> Unpacking is rarely needed. It matches some kind of problems.
Not needed, I suppose, since there is another way to write the code,
but using tuple unpacking can greatly reduce the length and improve
the readability of your code.
> Imagine you parse "codes" each made of name-sep-number. Then when walking through the result you can write:
> for code in codes:
> (name,sep,number) = code
Or even
for name, sep, number in codes:
# Do something with name, sep, number
> It's just an elegant manner to avoid indexing -- right?
It avoids indexing and gives meaningful names to values. Compare the
above with the alternatives:
for code in codes:
name = code[0]
sep = code[1]
number = code[2]
# Do something with name, sep, number
or
for code in codes:
# Do something with code[0], code[1], code[2]
The first alternative is much more verbose while the second one is
much harder to understand.
Kent
More information about the Tutor
mailing list