If I do this:
x=[(t,some_very_complex_computation(y)) for t in z]
Apparently some_very_complex_computation(y) is not dependent on t. So it should be evaluated only once. Is there any way to make Python aware of this, so it won’t evaluate some_very_complex_computation(y) for every iteration?
Edit: I really want to do that in one line…
Usually you should follow San4ez’s advise and just use a temporary variable here. I will still present a few techniques that might prove useful under certain circumstances:
In general, if you want to bind a name just for a sub-expression (which is usually why you need a temporary variable), you can use a lambda:
In this particular case, the following is a quite clean and readable solution:
A general note about automatic optimizations like these
In a dynamic language like Python, an implementation would have a very hard time to figure out that
some_very_complex_computationis referentially transparent, that is, that it will always return the same result for the same arguments. You might want to look into a functional language like Haskell if you want magic like that.“Explicit” pureness: Memoization
What you can do however is make
some_very_complex_computationexplicitly cache its return values for recent arguments:This is Python 3. In Python 2, you’d have to write the decorator yourself: