Generator that produces sequence 0,1,2,3,

Question:

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

It is easy to implement it:

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

But I suppose, this exists already in Python.

Asked By: habrewning

||

Answers:

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).

Answered By: Riccardo Bucco
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.