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?
Simply speaking, a generator is a function that returns an object (iterator) which we can iterate over (one value at a time).
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.
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.
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.
Simply
for x in gen: # whatever
will do the trick. Note that if gen
always returns True
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With