I just wrote a piece of code which drove home how simple and elegant generators in Python can be. I needed to loop through a very large number (lots and lots of digits) and though I needed only the string representation of the number, I couldn’t write the loop in the typical fashion since the number was too large for Python to handle.

This is what I came up with. Does anyone have suggestions on how I can make this prettier?

> def generate(prefix, remaining):
        if remaining ==0:
            yield prefix
        else:    
            for i in range(0,10):
                for number in generate(prefix + str(i), remaining-1):
                    yield number

for number in generate("", 25): #25 digit number
    print number

#

Come back for more! Subscribe via RSS or email.