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

asked Dec 16, 2011 at 14:37

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]
answered Dec 16, 2011 at 14:40
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]
answered Dec 16, 2011 at 14:40

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]
answered Dec 16, 2011 at 15:15

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

answered Dec 16, 2011 at 15:48

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.

answered Dec 16, 2011 at 14:41

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.