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

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Jan 16 06:23:34 EST 2009


On Fri, 16 Jan 2009 02:51:43 -0500, 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!!!
[...]
> I see what Python is doing -- lazy evaluation doesn't evaluate (x+(i*10)
> for x in count()) until the end.  But is this the right behaviour?  How
> can I get the output I want: [0, 1, 2, 3, 4]
> [10, 11, 12, 13, 14]

The solution I would use is:

itlist = [0,0]
for i in range(2):
    itlist[i] = ( lambda i: (x+(i*10) for x in count()) )(i)


Or pull the lambda out of the loop:


itlist = [0,0]
def gen(i):
    return (x+(i*10) for x in count())

for i in range(2):
    itlist[i] = gen(i)



-- 
Steven



More information about the Python-list mailing list