CARVIEW |
Generators
Generators are very useful and can help simplify your code and improve its performance.
Examples
For example, the RangeGenerator can be used to iterate over a large number of values, without creating a massive list (like range would)
1 #the for loop will generate each i (i.e. 1,2,3,4,5, ...), add it to sum, and throw it away
2 #before the next i is generated. This is opposed to iterating through range(...), which creates
3 #a potentially massive list and then iterates through it.
4 for i in irange(1000000):
5 sum = sum+i
Generators can be composed. Here we create a generator on the squares of consecutive integers.
1 #square is a generator
2 square = (i*i for i in irange(1000000))
3 #add the squares
4 for i in square:
5 sum = sum +i
Here, we compose a square generator with the takewhile generator, to generate squares less than 100
1 #add squares less than 100
2 square = (i*i for i in count())
3 bounded_squares = takewhile(lambda x : x< 100, square)
4 for i in bounded_squares:
5 sum += i
to be written: Generators made from classes?
Links
PEP-255: Simple Iterators -- the original
Python Generator Tricks -- various infinite sequences, recursions, ...
"weightless threads" -- simulating threads using generators
XML processing -- yes, using generators
C2:GeneratorsAreNotCoroutines -- particulars on generators, coroutines, and continuations
See also: Iterator
Discussion
I once saw MikeOrr demonstrate Before and After examples. But, I forget how they worked.
Can someone demonstrate here?
He did something like: Show how a normal list operation could be written to use generators. Something like:
1 def double(L):
2 return [x*2 for x in L]
3
4 eggs = double([1, 2, 3, 4, 5])
...he showed how that, or something like that, could be rewritten using iterators, generators.
It's been a while since I've seen it, I may be getting this all wrong.
-- LionKimbro 2005-04-02 19:12:19
EditText (last edited 2005-04-02 23:59:32 by LionKimbro)
DeleteCache (cached 2007-12-03 15:37:40)- Login
- Navigation
- Actions
- Your recent pages