[Python-ideas] Assignments in list/generator expressions

Mathias Panzenböck grosser.meister.morti at gmx.net
Sat Apr 9 06:29:44 CEST 2011


Before I go to bead another thing I miss in Python. In generator expressions you can unpack elements:
 >>> ys = [f(x1) for x1, x2 in xs]

But sometimes you need not just the unpacked elements but also the original tuple:
 >>> ys = [f(x1, (x1, x2)) for x1, x2 in xs]
or
 >>> ys = [f(x[0], x) for x in xs]

If you need x[0] often in your expression it would be nice if you could write something like this:
 >>> ys = [f(x1, x) for (x1, x2) as x in xs]

So the "as" keyword here would be like the "@" in Haskell. You don't need repetitive __getitem__ 
calls and also don't need to rebuild the tuple. Of course if Python would know that the type of 
whatever is unpacked is a tuple (which is immutalbe) optimizations could create the same bytecode 
from both old variants then from the new one.

Good night,
panzi



More information about the Python-ideas mailing list