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

Chris Rebert pyideas at rebertia.com
Sun Jun 21 11:06:18 CEST 2009

```> On Sun, Jun 21, 2009 at 10:36 AM, Lie Ryan<lie.1296 at gmail.com> wrote:
>> Ben Finney wrote:
>>> Lie Ryan <lie.1296 at gmail.com> writes:
>>>
>>>> Steven D'Aprano wrote:
>>>> <snip>
>>>>> 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.
>>>
>>> I think it would be more readable without index references, but instead
>>> using tuple unpacking::
>>>
>>>     gen = ((x, 3*x**2-5*x+4) for x in seq if x % 3 != 2)
>>>     result = [b for (a, b) in gen if -a < b < a]
>>>
>>> It can even be done as a single expression without (IMO) significantly
>>> affecting readability::
>>>
>>>     result = [
>>>         b for (a, b) in
>>>             ((x, 3*x**2-5*x+4) for x in seq if x % 3 != 2)
>>>         if -a < b < a]
>>
>> IMHO, when a comprehension requires more than a single line, it should
>> turn into explicit loop.
>>
>> <snip>
>>
On Sun, Jun 21, 2009 at 1:54 AM, Andrey Popp<8mayday at gmail.com> wrote:
> What about where/let expression?
> [(y, y) for x in some_list if y < 0 where y = f(x)]
> --
> С уважением, Андрей Попп.
> +7 911 740 24 91

(A) Please don't top-post. (http://en.wikipedia.org/wiki/Top-post)
(B) That has the distinct disadvantage of adding a new keyword. I
instead prefer the "as" version of the proposal for this reason.

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

```

More information about the Python-ideas mailing list