Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About Python's inner to outer evaluation order in generator expressions

When iterating over the following generator expression,

fun(i) for i in mylist if i not in setA.union(setB)

is the setA.union method called in each iteration, or only once?

like image 286
silvado Avatar asked Jan 15 '23 11:01

silvado


1 Answers

Simple proof using dis module:

In [24]: def func():
   ....:     a=set([1,2,3])
   ....:     b=set([3,4,5])
   ....:     c=[i for i in xrange(10) if i in a.union(b)]
   ....:     

In [25]: dis.dis(func)

  4          42 BUILD_LIST               0
             45 LOAD_GLOBAL              1 (xrange)
             48 LOAD_CONST               6 (10)
             51 CALL_FUNCTION            1
             54 GET_ITER                          #iterator returned from xrange

        >>   55 FOR_ITER                33 (to 91) #until the iterator is not exhausted
             58 STORE_FAST               2 (i)
             61 LOAD_FAST                2 (i)
             64 LOAD_FAST                0 (a)
             67 LOAD_ATTR                2 (union)
             70 LOAD_FAST                1 (b)
             73 CALL_FUNCTION            1      #union() is being called in each iteration
             76 COMPARE_OP               6 (in)
             79 POP_JUMP_IF_FALSE       55
             82 LOAD_FAST                2 (i)
             85 LIST_APPEND              2
             88 JUMP_ABSOLUTE           55
                                                         #end of loop    
        >>   91 STORE_FAST               3 (c)
             94 LOAD_CONST               0 (None)
             97 RETURN_VALUE 

So, for your example it is going to be called in each iteration i.e. len(mylist) times.

like image 98
Ashwini Chaudhary Avatar answered Jan 16 '23 23:01

Ashwini Chaudhary