Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 669
iTayb Avatar asked Jul 18 '12 10:07

iTayb


People also ask

Can you iterate through a generator?

Simply speaking, a generator is a function that returns an object (iterator) which we can iterate over (one value at a time).

How do you iterate through a generator object?

You need to call next() or loop through the generator object to access the values produced by the generator expression. When there isn't the next value in the generator object, a StopIteration exception is thrown. A for loop can be used to iterate the generator object.

How many times can you iterate through a generator?

This is because generators, like all iterators, can be exhausted. Unless your generator is infinite, you can iterate through it one time only. Once all values have been evaluated, iteration will stop and the for loop will exit.

Which function would you use to iterate over generator objects Python?

For an object to be an iterator it should implement the __iter__ method which will return the iterator object, the __next__ method will then return the next value in the sequence and possibly might raise the StopIteration exception when there are no values to be returned.


1 Answers

Simply

for x in gen:     # whatever 

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

like image 93
Sven Marnach Avatar answered Oct 20 '22 18:10

Sven Marnach