structured unpacking assignments

george young gry at
Fri Oct 22 17:53:02 CEST 2004

[python-2.3.3, x86 linux]
I came across an cool python feature that I've not seen discussed.
This may be *implied* by the language reference manual
[], but it was never
obvious to me: 

An assignment statement can unpack a sequence, binding it's values
to explicit names, e.g.:
  r,g,b = color_tuple

and most of us use this frequently.  However, what I never saw was
that the target list (r,g,b above) can also have non-trivial structure:

mylist = [('the', 'article'), ('house', 'noun'), ('run', 'verb')]
for n,(part,word) in enumerate(mylist):
    word_array[n] = Usage(part, word)

This actually feels a lot like lisp's macro destructure feature.
Taking it a bit farther:
[adapted from "Common Lisp", G.L. Steele Jr. 2nd Ed., Digital Press 1990]:

((mouth, eye1, eye2),
 ((fin1, len1),(fin2, len2)),
 tail) = \
    ((m, eyes[0], eyes[1]),
     ((f1, count_scales(f1)), (f2, count_scales(f2))),

Now, I think that pythoneers often use bare list/tuple structures
when a class would be much clearer, and I don't recommend managing halibut
data as in the example.  But the first example seems quite clear and natural.

Does anyone else have illustrious examples of structured unpacking?

-- George Young
"Are the gods not just?"  "Oh no, child.
What would become of us if they were?" (CSL)

More information about the Python-list mailing list