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
Didier Trosset
37.7k14 gold badges89 silver badges126 bronze badges
5 Answers 5
>>> 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
Kevin
76.5k13 gold badges141 silver badges168 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
eumiro
214k36 gold badges307 silver badges264 bronze badges
1 Comment
Michael J. Barber
never try this with floats as x and y
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
Abhijit
64k20 gold badges143 silver badges209 bronze badges
2 Comments
eumiro
numpy.array(range...)? Have a look at numpy.arangeWestCoastProjects
The
np.arange(0,N) *Y+X is useful.[x+i*y for i in xrange(1,10)]
will do the job
answered Dec 16, 2011 at 15:48
tarashish
1,97521 silver badges32 bronze badges
Comments
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
tdenniston
3,5592 gold badges24 silver badges31 bronze badges
Comments
Explore related questions
See similar questions with these tags.
lang-py