Re: how to make a generator use the last yielded value when it regains control
- From: "Ben Cartwright" <bencvt@xxxxxxxxx>
- Date: 6 Apr 2006 21:49:06 -0700
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
.
- References:
- how to make a generator use the last yielded value when it regains control
- From: John Salerno
- Re: how to make a generator use the last yielded value when it regains control
- From: Ben Cartwright
- Re: how to make a generator use the last yielded value when it regains control
- From: John Salerno
- how to make a generator use the last yielded value when it regains control
- Prev by Date: Re: Missing C modules in 2.5 on OS X?
- Next by Date: Re: confusing behaviour of os.system
- Previous by thread: Re: how to make a generator use the last yielded value when it regains control
- Next by thread: Re: how to make a generator use the last yielded value when it regains control
- Index(es):
Relevant Pages
|