J.Cole J.Cole - 5 months ago 18
Python Question

Change step value in 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

Answer

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
Comments