[Python-ideas] Accessing the result of comprehension's expression from the conditional

Lie Ryan lie.1296 at gmail.com
Sat Jun 20 20:26:57 CEST 2009

Steven D'Aprano wrote:
> The only case it doesn't cover is where the second filter depends on the 
> value of x, and even that can be covered with a *tiny* bit more work:
> gen = ((x, 3*x**2-5*x+4) for x in seq if x % 3 != 2)
> result = [y[1] for y in gen if -y[0] < y[1] < y[0]]
> It requires no new syntax, no changes to the behaviour of list comps, no 
> new meaning on "as", it's understandable and readable.
> Compare your suggestion:
> [3*x**2-5*x+4 as y for x in seq if (x % 3 != 2) and (-x < y < x)]

For me, this one is much clearer, understandable, and readable than y[0]
and y[1]; and you still have the option to split them if you think y[0]
and y[1] is better.

> Disadvantages:
> - It requires new syntax.
> - It requires new behaviour to list comps and generator expressions.
> - It creates yet another meaning to the keyword "as".

"as" is already used for renaming keyword in "with" and "import"
statement, so I don't think it actually creates any more meaning that we
don't already have.

More information about the Python-ideas mailing list