List comprehension with expensive computation

Viewed 311

So I have a few list comprehensions that look like the following.

li = [some_computation(x) for x in y if some_computation(x)]

Where I only want the values that are truthy with respect to some_computation.

  1. Does this compute some_computation(x) twice as the list comprehension makes it seem? If some_computation is expensive, I really don't want this. (I feel like this is probably the case :()
  2. Is there a better way to do this? Perhaps to break it into a regular for loop and append if only if some_computation(x), but I like comprehensions.
3 Answers
Related