Array initialization in Python


Question

I want to initialize an array with 10 values starting at X and incrementing by Y. I cannot directly use range() as it requires to give the maximum value, not the number of values.

I can do this in a loop, as follows:

a = []
v = X
for i in range(10):
    a.append(v)
    v = v + Y

But I'm certain there's a cute python one liner to do this ...

1
6
12/19/2011 1:50:59 PM

Accepted Answer

>>> x = 2
>>> y = 3
>>> [i*y + x for i in range(10)]
[2, 5, 8, 11, 14, 17, 20, 23, 26, 29]
15
12/16/2011 2:40:20 PM

You can use this:

>>> x = 3
>>> y = 4
>>> range(x, x+10*y, y)

[3, 7, 11, 15, 19, 23, 27, 31, 35, 39]

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon