habrewning
habrewning

Reputation: 1069

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

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.

Upvotes: 0

Views: 359

Answers (1)

Riccardo Bucco
Riccardo Bucco

Reputation: 15364

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

Upvotes: 3

Related Questions