pythonperformancelist-comprehensiondictionary-comprehensionset-comprehension

Cache variable in list comprehension


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?


Solution

  • Using the walrus:

    [cache for i in range(LARGE_NUMBER) if check(cache := expensive(i))]