How to create a list of a range with incremental step?

17,019

Solution 1

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

Solution 2

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]

Solution 3

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)]
Share:
17,019
Reman
Author by

Reman

Updated on June 17, 2022

Comments

  • Reman
    Reman almost 2 years

    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?

  • Reman
    Reman over 7 years
    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.
  • Marcel Cozma
    Marcel Cozma over 7 years
    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 wanted
  • Uchiha Itachi
    Uchiha Itachi over 7 years
    I'm a kinda new to these programming.
  • Uchiha Itachi
    Uchiha Itachi over 7 years
    Sure and Thanks Brother
  • Reman
    Reman over 4 years
    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,+ ....