Possible to capture the returned value from a Python list comprehension for use a condition?

Posted by Joe on Stack Overflow See other posts from Stack Overflow or by Joe
Published on 2012-01-06T16:57:40Z Indexed on 2012/03/26 23:29 UTC
Read the original article Hit count: 257

Filed under:
|

I want to construct a value in a list comprehension, but also filter on that value. For example:

[expensive_function(x) for x in generator where expensive_function(x) < 5]

I want to avoid calling expensive_function twice per iteration.

The generator may return an infinite series, and list comprehensions aren't lazily evaluated. So this wouldn't work:

[y in [expensive_function(x) for x in generator where expensive_function(x)] where y < 5]

I could write this another way, but it feels right for a list comprehension and I'm sure this is a common usage pattern (possible or not!).

© Stack Overflow or respective owner

Related posts about python

Related posts about list-comprehension