Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluation order in python list and tuple literals

Tags:

python

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?

like image 630
szli Avatar asked Jan 23 '13 19:01

szli


2 Answers

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.

like image 166
Ashwini Chaudhary Avatar answered Sep 28 '22 15:09

Ashwini Chaudhary


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

like image 33
mgilson Avatar answered Sep 28 '22 16:09

mgilson