szli
szli

Reputation: 39079

Evaluation order in python list and tuple literals

Let's say we have something like this:

a = (fcn1(), fcn2())
b = [fcn1(), fcn2()]

Does the Python interpreter evaluate fcn1() before fcn2(), or is the order undefined?

Upvotes: 12

Views: 1672

Answers (2)

mgilson
mgilson

Reputation: 309899

expressions are evaluated left to right. This link specifically treats the tuple case. Here's another link which specifically treats the list case.

Upvotes: 3

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250931

They are evaluated from left to right.

From the docs(for lists):

When a comma-separated list of expressions is supplied, its elements are evaluated from left to right and placed into the list object in that order.

Small test using dis.dis():

In [208]: def f1():pass

In [209]: def f2():pass

In [210]: import dis

In [212]: def func():

        a = (f1(), f2())
        b  = [f1(), f2()]
       .....:     

In [213]: dis.dis(func)
  2           0 LOAD_GLOBAL              0 (f1)
              3 CALL_FUNCTION            0
              6 LOAD_GLOBAL              1 (f2)
              9 CALL_FUNCTION            0
             12 BUILD_TUPLE              2
             15 STORE_FAST               0 (a)

  3          18 LOAD_GLOBAL              0 (f1)
             21 CALL_FUNCTION            0
             24 LOAD_GLOBAL              1 (f2)
             27 CALL_FUNCTION            0
             30 BUILD_LIST               2
             33 STORE_FAST               1 (b)
             36 LOAD_CONST               0 (None)
             39 RETURN_VALUE        

Note: In case of assignment, the right hand side is evaluated first.

Upvotes: 12

Related Questions