Possible to capture the returned value from a Python list comprehension for use a condition?
- by Joe
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!).