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

Discussion in 'Python' started by Boris Borcic, Jan 16, 2009.

  1. Boris Borcic

    Boris Borcic Guest

    The minimal correction, I guess, is to write

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

    instead of

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

    although

    itlist = (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 = (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
    > --
    > http://mail.python.org/mailman/listinfo/python-list
    >
    Boris Borcic, Jan 16, 2009
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. John Saunders
    Replies:
    0
    Views:
    464
    John Saunders
    Aug 28, 2003
  2. Nehmo Sergheyev
    Replies:
    1
    Views:
    504
    Andrew Urquhart
    May 9, 2004
  3. Marcin Vorbrodt

    ::std sometimes needed, sometimes not

    Marcin Vorbrodt, Sep 16, 2003, in forum: C++
    Replies:
    24
    Views:
    761
    Jerry Coffin
    Sep 17, 2003
  4. Ken Pu
    Replies:
    3
    Views:
    671
    Steven D'Aprano
    Jan 16, 2009
  5. Boris Borcic
    Replies:
    0
    Views:
    545
    Boris Borcic
    Jan 16, 2009
Loading...

Share This Page