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 ...
To initialize an array with the default value, we can use for loop and range() function in python language. Python range() function takes a number as an argument and returns a sequence of number starts from 0 and ends by a specific number, incremented by 1 every time.
The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.
To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15}; Or, you could generate a stream of values and assign it back to the array: int[] intArray = IntStream.
>>> x = 2
>>> y = 3
>>> [i*y + x for i in range(10)]
[2, 5, 8, 11, 14, 17, 20, 23, 26, 29]
You can use this:
>>> x = 3
>>> y = 4
>>> range(x, x+10*y, y)
[3, 7, 11, 15, 19, 23, 27, 31, 35, 39]
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]
[x+i*y for i in xrange(1,10)]
will do the job
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With