I want to know if there is a better and cleaner way of printing the 3rd step of a generator function.
Currently I have written the following code
def imparesgen():
n = 0
while n<200:
n=n+2
yield n
gen = imparesgen()
y = 0
for x in gen:
y+=1
if y == 3:
print(x)
This worked, but, is there maybe a simpler way of doing this? Without the use of a list.
>Solution :
From Itertools recipes:
def nth(iterable, n, default=None):
"Returns the nth item or a default value"
return next(islice(iterable, n, None), default)
Applied to your example:
import itertools
def imparesgen():
n = 0
while n<200:
n=n+2
yield n
gen = imparesgen()
print(next(itertools.islice(gen, 3, None)))