generator function

Mel Wilson mwilson at
Thu Aug 7 15:26:37 CEST 2003

In article <215fa0fc.0308070503.2344dd66 at>,
tom_chansky at (chansky) wrote:
>I read the following link about generator:
>but I am still not so clear on the use/purpose of a generator function
>other than the fact that a generator can retain the state of the local
>variables within the fuction body.  Can someone out there shed some
>lights on this topic or share about how/when you would ever use a
>generator function.

   A generator is a function that's "called like" a
sequence.  If you want to process a series of values using
"for ... in ..." you can either assemble the values into a
sequence, or if they're being computed in the first place
you can code the computation as a generator and save memory.

   In the built-in functions, `range` is a function that
returns a list, `xrange` an alternative that is (or acts
like) a generator.

   My latest example is from a program that cycled through
all the possible 4-tuples constructed to some criteria to
see which ones matched other criteria.  Code went something

        row_vals = ((1,2,3,4,5,6,7,8,9), (2,3,4), (1,3,5,7), (6,8))

        def possible_rows ():
            for a in row_vals[0]:
                for b in row_vals[1]:
                    for c in row_vals[2]:
                        for d in row_vals[3]:
                            yield (a, b, c, d)
        for row in possible_rows():
            # further computations on row

The actual program had row_vals built from user input, the
"further computations" involved several different rows, etc.
not as cut-and-dried as this example.

        Regards.        Mel.

More information about the Python-list mailing list