Leonid
Leonid

Reputation: 23490

Python multi-dimensional array initialization without a loop

Is there a way in Python to initialize a multi-dimensional array / list without using a loop?

Upvotes: 9

Views: 32586

Answers (12)

Eric O. Lebigot
Eric O. Lebigot

Reputation: 94595

Depending on your real needs, the de facto "standard" package Numpy might provide you with exactly what you need.

You can for instance create a multi-dimensional array with

numpy.empty((10, 4, 100))  # 3D array

(initialized with arbitrary values) or create the same arrays with zeros everywhere with

numpy.zeros((10, 4, 100))

Numpy is very fast, for array operations.

Upvotes: 9

0xAliHn
0xAliHn

Reputation: 19280

You can do by this way:

First without using any loop:

[[0] * n] * m

Secondly using simple inline list comprehension:

[[0 for column in range(n)] for row in range(m)]

Upvotes: 0

Mythical_Ewe
Mythical_Ewe

Reputation: 101

You can use N-dimensional array (ndarray). Here is the link to the documentation. http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html

Upvotes: -2

Jens Nyman
Jens Nyman

Reputation: 1216

The following does not use any special library, nor eval:

arr = [[0]*5 for x in range(6)]

and it doesn't create duplicated references:

>>> arr[1][1] = 2
>>> arr
[[0, 0, 0, 0, 0],
 [0, 2, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0]]

Upvotes: 8

Arnab Datta
Arnab Datta

Reputation: 5256

a = [[]]
a.append([1,2])
a.append([2,3])

Then

>>> a
[[1, 2], [2, 3]]

Upvotes: 2

Luke404
Luke404

Reputation: 10620

Python does not have arrays. It has other sequence types ranging from lists to dictionaries without forgetting sets - the right one depends on your specific needs.

Assuming your "array" is actually a list, and "initialize" means allocate a list of lists of NxM elements, you can (pseudocode):

  • for N times: for M times: add an element
  • for N times: add a row of M elements
  • write the whole thing out

You say you don't want to loop and that rules out the first two points, but why? You also say you don't want to write the thing down (in response to JacobM), so how would you exactly do that? I don't know of any other way of getting a data structure without either generating it in smaller pieces (looping) or explicitly writing it down - in any programming language.

Also keep in mind that a initialized but empty list is no better than no list, unless you put data into it. And you don't need to initialize it before putting data...

If this isn't a theoretical exercise, you're probably asking the wrong question. I suggest that you explain what do you need to do with that array.

Upvotes: 1

John La Rooy
John La Rooy

Reputation: 304463

Sure there is a way

arr = eval(`[[0]*5]*10`)

or

arr = eval(("[[0]*5]+"*10)[:-1])

but it's horrible and wasteful, so everyone uses loops (usually list comprehensions) or numpy

Upvotes: 13

razpeitia
razpeitia

Reputation: 1997

Recursion is your friend :D

It's a pretty naive implementation but it works!

dim = [2, 2, 2]

def get_array(level, dimension):
    if( level != len(dimension) ):
        return [get_array(level+1, dimension) for i in range(dimension[level])]
    else:
        return 0

print get_array(0, dim)

Upvotes: 3

John Kugelman
John Kugelman

Reputation: 362087

It depends on what you what to initialize the array to, but sure. You can use a list comprehension to create a 5×3 array, for instance:

>>> [[0 for x in range(3)] for y in range(5)]
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

>>> [[3*y+x for x in range(3)] for y in range(5)]
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14]]

Yes, I suppose this still has loops—but it's all done in one line, which I presume is the intended meaning of your question?

Upvotes: 2

Brian Hawkins
Brian Hawkins

Reputation: 2930

If you're doing numerical work using Numpy, something like

x = numpy.zeros ((m,n))
x = numpy.ones ((m,n))

Upvotes: 1

user108088
user108088

Reputation: 1168

I don't believe it's possible.

You can do something like this:

>>> a = [[0] * 5] * 5

to create a 5x5 matrix, but it is repeated objects (which you don't want). For example:

>>> a[1][2] = 1
[[0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0]]

You almost certainly need to use some kind of loop as in:

[[0 for y in range(5)] for x in range(5)]

Upvotes: 5

Jacob Mattison
Jacob Mattison

Reputation: 51072

Sure, you can just do

mylist = [
            [1,2,3],
            [4,5,6],
            [7,8,9]
         ]

Upvotes: 7

Related Questions