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
  • 534
  • 3
  • 14

2 Answers2

4

Using the walrus:

[cache for i in range(LARGE_NUMBER) if check(cache := expensive(i))]
Kelly Bundy
  • 15,040
  • 7
  • 22
  • 53
0

You could simulate a nested comprehension:

 [val for i in range(LARGE_NUMBER) for val in [expensive(i)] if check(val)]
Alain T.
  • 34,859
  • 4
  • 30
  • 47