lazy evaluation is sometimes too lazy... help please.

Scott David Daniels Scott.Daniels at Acm.Org
Fri Jan 16 18:07:41 CET 2009

Ken Pu wrote:
> Hi,  below is the code I thought should create two generates, it[0] =
> 0,1,2,3,4,5, and it[1] = 0,10,20,30,..., but they turn out to be the
> same!!!
> from itertools import *
> itlist = [0,0]
> for i in range(2):
>   itlist[i] = (x+(i*10) for x in count())
> ...
> print list(islice(itlist[0], 5))
> print list(islice(itlist[1], 5))
> ... -- lazy evaluation doesn't evaluate
>      (x+(i*10) for x in count())   until the end. 
Nope, that generator expression is evaluated in your assignment.
The expression   x+(i*10)  is evaluated at each step of the generator.
 > But is this the right behaviour?
It is the defined behavior.

For what you want:
     import itertools as it

     def count_from(base):
         for n in it.count():
             yield n + base

     itlist = [count_from(n) for n in range(2)]

--Scott David Daniels
Scott.Daniels at Acm.Org

More information about the Python-list mailing list