correct usage of a generator?

Tim jtim.arnold at gmail.com
Mon Nov 28 10:36:17 EST 2011


Hi, I need to generate a list of file names that increment, like this:
fname1
fname2
fname3 and so on.

I don't know how many I'll need until runtime so I figure a generator is called for.

def fname_gen(stem):
    i = 0
    while True:
        i = i+1
        yield '%s%d' % (stem,i)

blarg = fname_gen('blarg')
boo = fname_gen('boo')

n = 3
for w in range(0,n):
    in_name = blarg.next()
    out_name = boo.next()


This works, but is it the 'normal' way to accomplish the task when you don't know 'n' until run-time?
thanks,
--Tim



More information about the Python-list mailing list