Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Print the nth step of a Generator in an easy way

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading