Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension with expensive computation [duplicate]

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.
like image 964
Nate Stemen Avatar asked Oct 27 '25 05:10

Nate Stemen


1 Answers

some_computation will be calculated twice, to avoid this you could use filter to discard the falsy results:

li = list(filter(None, (some_computation(x) for x in y)))

Or use a nested generator expression as Jon Clements suggests:

li = [el for el in (some_computation(x) for x in y) if el]
like image 104
Chris_Rands Avatar answered Oct 29 '25 20:10

Chris_Rands



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!