Take the 2-minute tour ×

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:
            print gen.next()
        except StopIteration:

Is there a more pythonic way?

share|improve this question
I would suggest using break; not continue –  Jon Clements Jul 18 '12 at 10:47
I would actually do it this way in the case where the generator may throw an exception on an element, but you don't want to stop the iteration. –  robbrit Nov 29 '13 at 18:41
add comment

4 Answers

up vote 13 down vote accepted


for x in gen:
    # whatever

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

share|improve this answer
No, if gen doesn't always return True. If the op's function_that_returns_a_generator() returns None, gen evaluates to False in the if statement. –  drevicko May 4 '13 at 5:49
@drevicko: I was assuming that function_that_returns_a_generator() returns a generator (bold assumption, isn't it?). None is not a generator. –  Sven Marnach May 29 '13 at 21:33
add comment
for item in function_that_returns_a_generator(param1, param2):
    print item

You don't need to worry about the test to see if there is anything being returned by your function as if there's nothing returned you won't enter the loop.

share|improve this answer
add comment

Just treat it like any other iterable:

for val in function_that_returns_a_generator(p1, p2):
    print val

Note that if gen: will always be True, so it's a false test

share|improve this answer
add comment

If you want to manually move through the generator (i.e., to work with each loop manually) then you could do something like this:

    from pdb import set_trace()

    for x in gen:
        #do whatever you want with x at the command prompt
        #use pdb commands to step through each loop of the generator e.g., >>c #continue   
share|improve this answer
add comment

Your Answer


