Python multi-dimensional array initialization without a loop

Question:

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

Asked By: Leonid

||

Answers:

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?

Answered By: John Kugelman

Sure, you can just do

mylist = [
            [1,2,3],
            [4,5,6],
            [7,8,9]
         ]
Answered By: Jacob Mattison

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.

Answered By: Eric O Lebigot

I don’t believe it’s possible.

You can do something like this:

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

to create a 5×5 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)]
Answered By: user108088

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

x = numpy.zeros ((m,n))
x = numpy.ones ((m,n))
Answered By: Brian Hawkins

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

Answered By: John La Rooy

Recursion is your friend 😀

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)
Answered By: razpeitia

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.

Answered By: Luke404
a = [[]]
a.append([1,2])
a.append([2,3])

Then

>>> a
[[1, 2], [2, 3]]
Answered By: Arnab Datta

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]]
Answered By: Jens Nyman

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

Answered By: Mythical_Ewe

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)]
Answered By: 0xAliHn
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.