Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array initialization in Python

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

like image 362
Didier Trosset Avatar asked Dec 16 '11 14:12

Didier Trosset


People also ask

How do you initialize an array in Python?

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.

What is array initialization?

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.

How do you initialize an array of data?

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.


4 Answers

>>> x = 2
>>> y = 3
>>> [i*y + x for i in range(10)]
[2, 5, 8, 11, 14, 17, 20, 23, 26, 29]
like image 83
Kevin Avatar answered Nov 10 '22 11:11

Kevin


You can use this:

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

[3, 7, 11, 15, 19, 23, 27, 31, 35, 39]
like image 30
eumiro Avatar answered Nov 10 '22 12:11

eumiro


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]
like image 38
Abhijit Avatar answered Nov 10 '22 11:11

Abhijit


[x+i*y for i in xrange(1,10)]

will do the job

like image 2
tarashish Avatar answered Nov 10 '22 11:11

tarashish