How to loop through a generator

iTayb picture iTayb · Jul 18, 2012 · Viewed 90.5k times · Source

How can one loop through a generator? I thought about this way:

gen = function_that_returns_a_generator(param1, param2)
if gen: # in case the generator is null
    while True:
        try:
            print gen.next()
        except StopIteration:
            break

Is there a more pythonic way?

Answer

Sven Marnach picture Sven Marnach · Jul 18, 2012

Simply

for x in gen:
    # whatever

will do the trick. Note that if gen always returns True.