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

Does Python provide range() as generator?

Does Python already provide a function that generates the endless sequence 0,1,2,3,… ?

I mean this:

def gen_range():
  count = 0
  while True:
    yield count
    count = count + 1 

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 :

Yes it does. Check out the itertools.count built-in function. As you can read in the linked docs, you can set the starting number and also the step. Float numbers are also allowed.

Here’s how you can use it:

from itertools import count

for n in count():
    print(n)

This is going to print 0, 1, 2, 3, … (Be careful! This example won’t stop until you force it to stop somehow).

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