Tryer
Tryer

Reputation: 120

Making a repeating iterator over a range of digits?

I'm trying to make an iterator that prints the repeating sequence

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, ...

I want an iterator so I can use .next(), and I want it to loop around to 0 when .next() is called while the iterator is at 9. But the thing is that I'll probably have a lot of these, so I don't just want to do itertools.cycle([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).

I don't want to have that many repeated lists of the same sequence in memory. I'd rather have the function x + 1 % 10 in each of the iterators and just have the iterator increment x every time next is called. I can't seem to figure out how to do this though with itertools. Is there a pythonic way of doing this?

Upvotes: 0

Views: 58

Answers (4)

Mike Müller
Mike Müller

Reputation: 85492

You can write an generator that uses range

def my_cycle(start, stop, step=1):
    while True:
        for x in range(start, stop, step):
            yield x

c = my_cycle(0, 10)

Upvotes: 3

Phydeaux
Phydeaux

Reputation: 2855

You can use a custom generator like this:

def single_digit_ints():
    i = 0
    while True:
        yield i
        i = (i + 1) % 10

for i in single_digit_ints():
    # ...

Upvotes: 1

jpp
jpp

Reputation: 164733

This is one way via itertools:

import itertools

def counter():
    for i in itertools.count(1):
        yield i%10

g = counter()

Upvotes: 1

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 96098

You can use your own custom generator:

def cycle_range(xr):
    while True:
        for x in xr:
            yield x

Assuming you are on Python 2, use:

r = xrange(9)
it1 = cycle_range(xr)
it2 = cycle_range(xr)

For memory efficiency.

Upvotes: 2

Related Questions