7

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 ...

5 Answers 5

17
>>> x = 2
>>> y = 3
>>> [i*y + x for i in range(10)]
[2, 5, 8, 11, 14, 17, 20, 23, 26, 29]
Sign up to request clarification or add additional context in comments.

Comments

9

You can use this:

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

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

1 Comment

never try this with floats as x and y
2

Just another way of doing it

Y=6
X=10
N=10
[y for x,y in zip(range(0,N),itertools.count(X,Y))]
[10, 16, 22, 28, 34, 40, 46, 52, 58, 64]

And yet another way

map(lambda (x,y):y,zip(range(0,N),itertools.count(10,Y)))
[10, 16, 22, 28, 34, 40, 46, 52, 58, 64]

And yet another way

import numpy
numpy.array(range(0,N))*Y+X
array([10, 16, 22, 28, 34, 40, 46, 52, 58, 64])

And even this

C=itertools.count(10,Y)
[C.next() for i in xrange(10)]
[10, 16, 22, 28, 34, 40, 46, 52, 58, 64]

2 Comments

numpy.array(range…)? Have a look at numpy.arange
The np.arange(0,N) *Y+X is useful.
2
[x+i*y for i in xrange(1,10)]

will do the job

Comments

1

If I understood your question correctly:

Y = 6
a = [x + Y for x in range(10)]

Edit: Oh, I see I misunderstood the question. Carry on.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.