armin
armin

Reputation: 651

Python looping back in a range when stop is exceed a value?

I have a range in like below. What I am trying to do is to loop back to 0 if the range stop is greater that a certain value (this example 96). I can simply loop through the range as I did below, but is there a better way to do perform this in Python's range?

my_range = range(90, 100)

tmp_list=[]
for i in range(90, 100):
    if i >= 96:
        tmp_list.append(i-96)
    else:
        tmp_list.append(i)

print(tmp_list)
[90, 91, 92, 93, 94, 95, 0, 1, 2, 3]

Upvotes: 0

Views: 570

Answers (2)

Azuuu
Azuuu

Reputation: 894

Checkout itertools.cycle:

from itertools import cycle

def clipped_cycle(start, end):
    c = cycle(range(0, 96))
    
    # Discard till start
    for _ in range(start):
        next(c)
        
    return c

c = clipped_cycle(90, 96)

for i in c:
    print(i)

what you get is an infinite output stream that cycles along.

90
91
92
93
94
95
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.
.
.

to get a limited number of outputs:

n = 7
for _ in range(n):
    print(next(c))

gives

90
91
92
93
94
95
0

Upvotes: 1

seVenVo1d
seVenVo1d

Reputation: 426

First, I did not understand why you have defined my_range = range(90, 100), if you are never going to use it.

You can use 'mod' in these cases.

Try this, short and effective

xlist = [i%96 for i in range(90,100)]

Upvotes: 0

Related Questions