[Python-ideas] Assignments in list/generator expressions

Chris Rebert pyideas at rebertia.com
Sat Apr 9 07:23:46 CEST 2011


On Fri, Apr 8, 2011 at 9:22 PM, Mathias Panzenböck
<grosser.meister.morti at gmx.net> wrote:
>
> I often have things like this:
> >>> ys = [f(x) for x in xs if f(x)]
>
> Obviously there is a redundant function call. You could rephrase that code to the following in order to avoid it:
> >>> ys = [y for y in (f(x) for x in xs) if y]
>
> But I think this is cumbersome and the extra generator overhead is unnecessary.
>
> So I propose this syntax:
> >>> ys = [f(x) as y for x in xs if y]
>
> It could be transformed to this:
> >>> ys = []
> >>> for x in xs:
> >>>    y = f(x)
> >>>    if y:
> >>>       ys.append(y)
>
> It's 6:18am here so I might not think straight and there is something fundamentally wrong with this. So please flame away.

This has been proposed previously:
http://mail.python.org/pipermail/python-ideas/2009-June/004946.html
(The syntax variant using "as" comes up part of the way through the thread.)

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-ideas mailing list