[Python-ideas] Assignments in list/generator expressions

Joao S. O. Bueno jsbueno at python.org.br
Mon Apr 11 02:56:07 CEST 2011


On Sat, Apr 9, 2011 at 1:22 AM, 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.
>

>>> ys = [f(x) as y for x in xs if y]
I supose the above example could be expressed like this:

ys = filter(None, (f(x) for x in xs))

(or

ys = list( filter(None, (f(x) for x in xs)))

if you happen to really need a list
)
In nearly any python version. And in doing so, I join the chorus of
-1 for such assignment possibilities.

And I am one that  likes doing big things in one liners from time to time,
just for the fun of it - while in-generator assignment would turn
these one liners much more flexible, it would, as several others
have pointed, imply in the possibility of having rather unreadable code
inside programs.

Regards,

  js
 -><-


>        -panzi



More information about the Python-ideas mailing list