Python: If an iterator is an expression, is it calculated every time?

Take the following example:

>>> for item in [i * 2 for i in range(1, 10)]: print item 2 4 6 8 10 12 14 16 18 

Is [i * 2 for i in range(1, 10)] calculated every time through the loop, or only once and saved? (Also, what is the name for this part of the expression?)

One of the reasons I want to do this is because I want the results of this list comprehension to be available in a loop.

+4
source share
3 answers

A good translation for i in <whatever>: <loopbody> showing what exactly it does for any <whatever> and any <loopbody> :

 _aux = iter(<whatever>) while True: try: i = next(_aux) except StopIteration: break <loopbody> 

except that the pseudo-variable that I call _aux here actually remains unnamed.

So, <whatever> always evaluated only once (to get iter() from it), and the resulting iterator will be next ed until it ends (if the <loopbody> ) has no break ).

Using listcomp, as you used, evaluation creates a list object (which in your code example remains unnamed). In a very similar code:

 for item in (i * 2 for i in range(1, 10)): ... 

using the xp gene rather than listcomp (syntax, parentheses instead of listcomp square brackets), it is next() , which actually does most of the work ( i progresses and doubles it) instead of dumping all the work at build time - it takes less temporary memory and can save time if the body of the loop can reasonably break exit earlier, but, with the exception of such special conditions (very tight memory or probable early termination of the loop), a listcomp can usually be (a little bit).

+5
source

In this case, you create a list in memory, and then iterate the contents of the list, so yes, it is calculated once and saved. it is nothing but to do

 i for i in [2,4,6,8]: print(i) 

If you do iter (i * 2 for i in xrange (1,10)), you get an iterator that evaluates at each iteration.

+3
source

All members of the expression list are evaluated once and then repeated.

In Python 2.x, the variable used in LC leaks into the parent scope, but since the LC has already been evaluated, the only available value is the one used to generate the end element in the resulting list.

+3
source

Source: https://habr.com/ru/post/1314144/


All Articles