What does generator comprehension do? How does it work? I couldn\'t find a tutorial about it.
Generator comprehension is an easy way of creating generators with a certain structure. Lets say you want a generator
that outputs one by one all the even numbers in your_list
. If you create it by using the function style it would be like this:
def allEvens( L ):
for number in L:
if number % 2 is 0:
yield number
evens = allEvens( yourList )
You could achieve the same result with this generator comprehension expression:
evens = ( number for number in your_list if number % 2 == 0 )
In both cases, when you call next(evens)
you get the next even number in your_list
.