A list comprehension executes the expression for each iteration.
sum(L)
is executed for each x in L
. Calculate it once outside the list comprehension:
s = sum(L)
A = [x/s for x in L]
Python has no way of knowing that the outcome of sum(L)
is stable, and cannot optimize the call away for you.
sum()
could be rebound to a different function that returns random values. The elements in L
could implement __add__
methods that produce side effects; the built-in sum()
would be calling these. L
itself could implement a custom __iter__
method that alters the list in-place as you iterate, affecting both the list comprehension and the sum()
call. Any of those hooks could rebind sum
or give x
elements a __div__
method that alters sum
, etc.
In other words, Python is too dynamic to accurately predict expression outcomes.