How to loop through a generator

In case you don't need the output of the generator because you care only about its side effects, you can use the following one-liner:

for _ in gen: pass

Follow up

Following the comment by aiven I made some performance tests, and while it seems that list(gen) is slightly faster than for _ in gen: pass, it comes out that tuple(gen) is even faster. However, as Erik Aronesty correctly points out, tuple(gen) and list(gen) store the results, so my final advice is to use

tuple(gen)

but only if the generator is not going to loop billions of times soaking up too much memory.


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.


You can simply loop through it:

>>> gen = (i for i in range(1, 4))
>>> for i in gen: print i
1
2
3

But be aware, that you can only loop one time. Next time generator will be empty:

>>> for i in gen: print i
>>> 

Simply

for x in gen:
    # whatever

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