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.
CodePudding user response:
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)))
CodePudding user response:
You could iterate over the generator three times. Since zip
stops at the shortest input, you'll only get three iterations provided gen
yields at least three elements.
gen = imparesgen()
for _, item in zip(range(3), gen):
pass
# Now, item is the third element
print(item)
Alternatively, use the next()
function to get the next element of the generator:
gen = imparesgen()
next(gen)
next(gen)
item = next(gen)
print(item)
Or, if you don't want to write out those next
lines multiple times:
gen = imparesgen()
for _ in range(3):
item = next(gen)
print(item)
CodePudding user response:
Is this what you're looking for?:
from itertools import islice
def imparesgen():
n = 0
while n<200:
n=n 2
yield n
gen = imparesgen()
third = list(islice(gen, 2, 3))[0] # -> 6
CodePudding user response:
Since a generator acts like an iterator, you can call next
on it :
third = next(next(next(gen)))
I don't think you can go much faster than that in pure-Python. But I think that without benchmarking the code, the speedup won't be noticed.