James Erickson
James Erickson

Reputation: 25

Expression evaluation order in Python

I'd like this question answered just for curiosity's sake. In the following mathematical expression (and ones like it):

(( (3 * 7)  + 5 * ((3 - 7) + (3 * 4))) + 9)

Does Python evaluate (3 - 7) or (3 * 4) first? The thing about this is, these innermost parentheses could really be evaluated in either order and achieve the same result. But which order is used?

At this point I'm considering putting a breakpoint in the actual Python interpreter to see if I can come up with any sort of answer (as to how the parse tree is generated). Been asking on IRCs and such to no avail. Thanks for your time.

Upvotes: 2

Views: 1258

Answers (2)

MisterMiyagi
MisterMiyagi

Reputation: 50076

You can inspect the byte code to see that the left side is evaluated first:

dis.dis("""(a - b) + (c * d)""")
  1           0 LOAD_NAME                0 (a)
              2 LOAD_NAME                1 (b)
              4 BINARY_SUBTRACT
              6 LOAD_NAME                2 (c)
              8 LOAD_NAME                3 (d)
             10 BINARY_MULTIPLY
             12 BINARY_ADD
             14 RETURN_VALUE

The evaluation order of expressions is part of the language specification.

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.


Note that if you use a literal expression, such as (3 - 7) + (3 * 4), it is not evaluated but directly compiled.

dis.dis("""(3 - 7) + (3 * 4)""")
  1           0 LOAD_CONST               0 (8)
              2 RETURN_VALUE

Upvotes: 8

Chris_Rands
Chris_Rands

Reputation: 41158

It evaluates left-to-right, you can check with with input() calls:

>>> (( (3 * 7) + 5 * ((input('1')) + (input('2')))) + 9)
1

Upvotes: 1

Related Questions