Reputation: 1147
Will the order of execution of the LHS and RHS of a python operator (such as multiplication) be in reading order? Equivalently is the code below guaranteed to calculate 30?
x = [1, 2, 3, 4]
result = 0
while x:
result += len(x) * x.pop()
assert 4**2 + 3**2 + 2**2 + 1**2 == result
print(result)
If the len(x)
is executed after the x.pop()
the result will not be 30.
I'm not so much interested in the answer for particular implementations of Python, more whether the language has guarantees on the order of evaluation.
Upvotes: 0
Views: 308
Reputation: 804
Yes, that is guaranteed to evaluate to 30.
https://docs.python.org/3/reference/expressions.html#evaluation-order
6.16. Evaluation order
Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.
Upvotes: 2