How to loop through a generator

Viewed 128183

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?

7 Answers

The other answers are good for complicated scenarios. If you simply want to stream the items into a list:

x = list(generator)

For simple preprocessing, use list comprehensions:

x = [tup[0] for tup in generator]

If you just want to execute the generator without saving the results, you can skip variable assignment:

# no var assignment b/c we don't need what print() returns
[print(_) for _ in gen]

Don't do this if your generator is infinite (say, streaming items from the internet). The list construction is a blocking op that won't stop until the generator is empty.

Related