1

Lets say I have an expensive operation expensive(x: int) -> int and the following list comprehension:

# expensive(x: int) -> int
# check(x: int) -> bool
[expensive(i) for i in range(LARGE_NUMBER) if check(expensive(i))]

If I want to avoid running expensive(i) twice for each i, is there any way to save it's value with list comprehension?

Throckmorton
  • 564
  • 4
  • 17

2 Answers2

5

Using the walrus:

[cache for i in range(LARGE_NUMBER) if check(cache := expensive(i))]
Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65
0

You could simulate a nested comprehension:

 [val for i in range(LARGE_NUMBER) for val in [expensive(i)] if check(val)]
Alain T.
  • 40,517
  • 4
  • 31
  • 51