简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM