PEP 255: Simple Generators

Tim Peters tim.one at home.com
Sun Jun 24 05:56:17 EDT 2001


[Tim]
> ... A good user's intro to Python generators doesn't exist yet (AFAIK).

[Michael Hudson]
> And writing one's going to be tricky, 'cause a generator is only a big
> win when there's lots of state that has to be maintained across yields
> and such an example is necessarily hairy.  Same deal for weak refs -
> a simple example is necessarily contrived.

Well, it depends on the audience and the author.  Generators don't have to
be terribly fancy to be useful, and in some contexts they're screamingly
natural.  For example, "how do I generate the elements of a list taken k at
a time?" is almost a c.l.py FAQ, and generators are ideal for that kind of
thing:

def gcomb(x, k):
    "Generate all combinations of k elements from list x."

    if k > len(x):
        return
    if k == 0:
        yield []
    else:
        first, rest = x[0], x[1:]
        # A combination does or doesn't contain first.
        # If it does, the remainder is a k-1 comb of rest.
        for c in gcomb(rest, k-1):
            c.insert(0, first)
            yield c
        # If it doesn't contain first, it's a k comb of rest.
        for c in gcomb(rest, k):
            yield c

seq = range(1, 5)
for k in range(len(seq) + 2):
    print "%d-combs of %s:\n    " % (k, seq),
    for c in gcomb(seq, k):
        print c, " ",
    print

Which prints:

0-combs of [1, 2, 3, 4]:
     []
1-combs of [1, 2, 3, 4]:
     [1]   [2]   [3]   [4]
2-combs of [1, 2, 3, 4]:
     [1, 2]   [1, 3]   [1, 4]   [2, 3]   [2, 4]   [3, 4]
3-combs of [1, 2, 3, 4]:
     [1, 2, 3]   [1, 2, 4]   [1, 3, 4]   [2, 3, 4]
4-combs of [1, 2, 3, 4]:
     [1, 2, 3, 4]
5-combs of [1, 2, 3, 4]:

This *kind* of example doesn't appeal to everyone, of course, but I already
covered my butt by saying it depends on the audience and the author <wink>.

i-write-best-when-the-audience-is-me-ly y'rs  - tim





More information about the Python-list mailing list