Array initialization in Python

17,005

Solution 1

>>> x = 2
>>> y = 3
>>> [i*y + x for i in range(10)]
[2, 5, 8, 11, 14, 17, 20, 23, 26, 29]

Solution 2

You can use this:

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

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

Solution 3

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]

Solution 4

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

will do the job

Solution 5

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.

Share:
17,005
Didier Trosset
Author by

Didier Trosset

Didier Trosset has been a professional programmer for 25 years. He started his career with a couple of video games titles published on Mac and PlayStation. After an attempt to create his own start-up, he chooses a geographical relocation closer to his origins, near Geneva in the Alps. From this point in time, he has been working in Switzerland. He first wrote computer programs for a cable and satellite pay TV provider, controlling the data streams that were traveling back and forth from the Earth to televisions. He then joined a small company named Acqiris, writing Linux device drivers for High-Speed Digitizer PCI cards. Acqiris was bought out in late 2006 by Agilent Technologies, where he has continued spreading Linux support to other instruments. The Electronics Measurement Group of Agilent Technologies then became Keysight Technologies. In August 2017, the PCIe High-Speed Digitizer business spun off from Keysight, giving birth for the second time to Acqiris. Specialties: C++ programming, Python programming, Debian GNU/Linux, device drivers

Updated on June 14, 2022

Comments

  • Didier Trosset
    Didier Trosset about 2 years

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

  • Michael J. Barber
    Michael J. Barber over 12 years
    never try this with floats as x and y
  • eumiro
    eumiro over 12 years
    numpy.array(range…)? Have a look at numpy.arange
  • WestCoastProjects
    WestCoastProjects almost 7 years
    The np.arange(0,N) *Y+X is useful.