[Python-ideas] Assignments in list/generator expressions

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


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.

	-panzi



More information about the Python-ideas mailing list