Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: lazy evaluation is sometimes too lazy... help please.

Thread Tools

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

Boris Borcic
Posts: n/a
The minimal correction, I guess, is to write

itlist[i] = (x+(i*10) for i in [i] for x in count())

instead of

itlist[i] = (x+(i*10) for x in count())


itlist[i] = (x+(i*10) for i,s in (i,count()) for x in s)

will better mimic generalizations in the sense that the "minimal correction"
delays the evaluation of count(), which doesn't matter in the case of count(),
but might make a difference if you replace it with some other expression.

The point is that the first iterator-producing expression in a generator
expression - eg the <X> in (<exp> for vars in <X>...) - is evaluated immediately
in the surrounding context, in contrast to the rest of the genexp.

Cheers, BB

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 "what's in the bags:"
> print list(islice(itlist[0], 5))
> print list(islice(itlist[1], 5))
> The output is:
> [10, 11, 12, 13, 14]
> [10, 11, 12, 13, 14]
> 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]
> Thanks.
> Ken
> --

Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
lazy evaluation is sometimes too lazy... help please. Ken Pu Python 3 01-16-2009 11:23 AM
Re: lazy evaluation is sometimes too lazy... help please. Boris Borcic Python 0 01-16-2009 10:46 AM
hello! first post to clr. I'm asking about an attempt at a lazy rubysolution to computing fibonacci numbers for a project euler problem. seems tobe a bug in lazy ruby... tphyahoo Ruby 6 08-08-2008 08:15 PM
Lazy evaluation: overloading the assignment operator? sturlamolden Python 9 05-03-2007 12:33 PM
Another method of lazy, cached evaluation. Python 3 01-19-2006 04:11 AM