How to create a list of a range with incremental step?
Asked Answered
F

4

8

I know that it is possible to create a list of a range of numbers:

list(range(0,20,1))
output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

but what I want to do is to increment the step on each iteration:

list(range(0,20,1+incremental value)

p.e. when incremental = +1

expected output: [0, 1, 3, 6, 10, 15]  

Is this possible in python?

Fourscore answered 20/11, 2016 at 15:48 Comment(3)
When incremental_value is one, the result would be [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]. Or do you want to increment the step by one on each iteration?Allyson
@ForceBru, your right. What I want is to add the incremental value to the step to become the new step value p.e. step = 1+1 =2, new step =2, new step = 3, new step = 4 etc. Yes increment the step by one on each iteration.Fourscore
Either use a while loop, or a generator (generators can store state of step, whereas iterators can't) as per the top-two answers here.Lagrange
A
11

This is possible, but not with range:

def range_inc(start, stop, step, inc):
    i = start
    while i < stop:
        yield i
        i += step
        step += inc
Allyson answered 20/11, 2016 at 15:56 Comment(0)
A
5

You can do something like this:

def incremental_range(start, stop, step, inc):
    value = start
    while value < stop:
        yield value
        value += step
        step += inc

list(incremental_range(0, 20, 1, 1))
[0, 1, 3, 6, 10, 15]
Adamson answered 20/11, 2016 at 15:55 Comment(1)
Thanks Batman, you gave the same answer as ForceBru. I gave the acceptance to his answer only because he was 1 minute earlier :) However I appreciate your answer very much.Fourscore
S
5

Even though this has already been answered, I found that list comprehension made this super easy. I needed the same result as the OP, but in increments of 24, starting at -7 and going to 7.

lc = [n*24 for n in range(-7, 8)]
Sorensen answered 31/7, 2019 at 22:30 Comment(1)
Or this one list(range(-168, 169, 24)) but it is not what I asked. I asked for an incremental increment. [0, 1, 3, 6, 10, 15] +1,+2,+3,+4,+5,+ ....Fourscore
L
-1

I have simplified the above code even further. Think this will do the trick.

List=list(range(1,20))
a=0
print "0"
for i in List:
    a=a+i
    print a

Specifying the nth range, gives you all the numbers with the particular pattern.

Lyse answered 20/11, 2016 at 16:18 Comment(3)
where is b used and why use "l" ? "Never use the characters 'l' (lowercase letter el), 'O' (uppercase letter oh), or 'I' (uppercase letter eye) as single character variable names. In some fonts, these characters are indistinguishable from the numerals one and zero. When tempted to use 'l', use 'L' instead." (legacy.python.org/dev/peps/pep-0008/#names-to-avoid) Also your code doe not output a list, as Reman wantedGluttonous
I'm a kinda new to these programming.Lyse
Sure and Thanks BrotherLyse

© 2022 - 2024 — McMap. All rights reserved.