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

Tal Einat taleinat at gmail.com
Fri Jun 19 16:34:15 CEST 2009

On Fri, Jun 19, 2009 at 4:45 PM, Jim Jewett<jimjjewett at gmail.com> wrote:
> On Fri, Jun 19, 2009 at 7:34 AM, Tal Einat<taleinat at gmail.com> wrote:
>> Just using [f(x) for x in nums if f(x) > 0] is the most readable and
>> obvious option.
> I would often prefer to break it into two steps:
>    temp = (f(x) for x in nums)
>    results = [e for e in temp if e>0]

I sometimes find myself doing that too. That's probably more readable
than what I wrote :)

> Others will dislike the extra line and temp var, which is one reason
> it isn't among the several solutions previously suggested.

I sometimes avoid the temporary variable by using the same one twice, e.g.:
results = (f(x) for x in nums)
results = [res for res in results if res > 0]

In the above example the second line is just filtering the results,
and I feel this idiom conveys the idea pretty well.

- Tal

More information about the Python-ideas mailing list