Generators and Iterators in Python

A generator function "yields" its values rather than returning them – and one generator function can yield zero or more results:

def alphabet (): # This is a generator.
   for c in "abcdefghijklmnopqrstuvwxyz":
      yield c
for a in alphabet (): # This is an iterator.
   print a,
# result:
# a b c d e f g h i j k l m n o p q r s t u v w x y z
All About Pattern Matching Sam Wilmott
Slide 30 of 37        www.wilmott.ca