how to make a generator use the last yielded value when it regains control

Ben Cartwright bencvt at gmail.com
Fri Apr 7 00:49:06 EDT 2006


John Salerno wrote:
> Actually I was just thinking about this and it seems like, at least for
> my purpose (to simply return a list of numbers), I don't need a
> generator.

Yes, if it's just a list of numbers you need, a generator is more
flexibility than you need.  A generator would only come in handy if,
say, you wanted to give your users the option of getting the next N
items in the sequence, *without* having to recompute everything from
scratch.


> My understanding of a generator is that you do something to
> each yielded value before returning to the generator (so that you might
> not return at all),

A generator is just an object that spits out values upon request; it
doesn't care what the caller does with those values.

There's many different ways to use generators; a few examples:

# Get a list of the first 10
from itertools import islice
m = [n for n in islice(morris(1), 10)]

# Prompt user between each iteration
for n in morris(1):
    if raw_input('keep going? ') != 'y':
        break
    print n

# Alternate way of writing the above
g = morris(1)
while raw_input('keep going? ') == 'y':
    print g.next()

--Ben




More information about the Python-list mailing list