Revision 1 as of 2004-11-11 18:09:07

Clear message

Generators are very useful and can help simplify your code and improve its performance.

simple examples

For example, the RangeGenerator can be used to iterate over a large number of values, without creating a massive list (like range would)

#the for loop will generate each i (i.e. 1,2,3,4,5, ...), add it to sum,  and throw it away
#before the next i is generated.  This is opposed to iterating through range(...), which creates
#a potentially massive list and then iterates through it.
for i in irange(1000000):
   sum = sum+i

Generators can be composed. Here we create a generator on the squares of consecutive integers.

#square is a generator 
square = (i*i for i in irange(1000000))
#add the squares
for i in square:
   sum = sum +i

Here, we compose a square generator with the takewhile generator, to generate squares less than 100

#add squares less than 100
square = (i*i for i in count())
bounded_squares = takewhile(lambda x : x< 100, square)
for i in bounded_squares:
   sum += i

Unable to edit the page? See the FrontPage for instructions.