Idea for improved tuple unpacking

Michael Haggerty mhagger at alum.mit.edu
Thu Oct 19 23:14:22 EDT 2000


Hi,

In my code the following idiom is pretty common:

    (first,second) = t[:2]
    rest = t[2:]

(t is a tuple).  Other scripting languages (Perl, REXX, ...) have a
way to do this sort of thing in one statement.  Then it occurred to me
that by analogy with function declaration syntax, it would be cool to
be able to do

    (first,second,*rest) = t

This would be functionally equivalent to the above: rest would be set
equal to a tuple containing the `rest' of t--the part following its
first two elements.  The same thing should work for lists.

I think this notation is obvious, has an obvious precedent in Python,
and is less error-prone than the current option (particularly when you
have to change the number of `fixed' values).  I don't think it would
conflict with current Python syntax.  Opinions?

Unfortunately I don't know enough about parsing to try to implement
it...

An extension of this idea would allow a single variable element to
appear anywhere in an assigned-to list:

    (*head, second_to_last, last) = t
    (first, *middle, last) = t

But now I'm probably getting carried away.

Michael

-- 
Michael Haggerty
mhagger at alum.mit.edu



More information about the Python-list mailing list