Search code examples
pythongenerator

How to loop through a generator


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?


Solution

  • Simply

    for x in gen:
        # whatever
    

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