Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change step value inside range function?

list1 = [1, 2, 3, 4]

i'm trying to figure out a way to change the step value for each printed i

What I've tried

r = 0
for i in range(0, 10, list1[r]):
    print i
    r = r + 1
like image 252
J.Cole Avatar asked Aug 17 '26 10:08

J.Cole


1 Answers

I would suggest implementing a generator of your own for this using while loop. Example -

def varied_step_range(start,stop,stepiter):
    step = iter(stepiter)
    while start < stop:
        yield start
        start += next(step)

Then you can use this as -

for i in varied_step_range(start,stop,steplist):
    #Do your logic.

We do the step = iter(stepiter)so that stepiter can be any kind of iterable.


Demo -

>>> def varied_step_range(start,stop,stepiter):
...     step = iter(stepiter)
...     while start < stop:
...         yield start
...         start += next(step)
... 
>>> for i in varied_step_range(0,10,[1,2,3,4]):
...     print i
... 
0
1
3
6
like image 162
Anand S Kumar Avatar answered Aug 19 '26 13:08

Anand S Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!