Python generator fun

I know Python’s iterators and generators aren’t that new anymore, but at heart I’m still a Python 1.5 programmer. I’ve come to iterators and generators in Python from my experience in JavaScript.

This morning I wanted to generate a list of names (for nodes in my NFA/DFA pattern matching code) that looked like: 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, AA, AB, AC, AD, AE, AF, AG, AH, AI, AJ, AK, AL, AM, AN, AO, AP, AQ, AR, AS, AT, AU, AV, AW, AX, AY, AZ, BA, BB, BC, BD, etc… A couple of minutes of fiddling I came up with:

def name_generator():
  from string import uppercase
  from itertools import chain
  for n in chain([''], name_generator()):
    for c in uppercase:
      yield n+c

It think the code is pretty simple, pretty readable, and pretty efficient. It’s not rocket science, but I feel that iterators and generators have paid off well for Python.

One reply on “Python generator fun”

  1. Thanks for that, I hadn’t really looked at generators before and playing with your snippet there was a good way to get started!

Comments are closed.