Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 810
Reman Avatar asked Nov 20 '16 15:11

Reman


People also ask

How do you increment a value in a list Python?

Python integers are not mutable, but lists are. In the first case el references immutable integers, so += creates a new integer that only el refers to. In the second case the list a is mutated directly, modifying its elements directly.


3 Answers

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
like image 75
ForceBru Avatar answered Sep 20 '22 08:09

ForceBru


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]
like image 32
Batman Avatar answered Sep 19 '22 08:09

Batman


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)]
like image 23
bearcub Avatar answered Sep 22 '22 08:09

bearcub