Revision 2 as of 2004-11-17 05:53:23

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)

   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

Generators made from classes?

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