Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python multi-dimensional array initialization without a loop

Tags:

python

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

like image 756
Leonid Avatar asked Sep 07 '10 20:09

Leonid


2 Answers

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]]
like image 186
Jens Nyman Avatar answered Oct 23 '22 12:10

Jens Nyman


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)]
like image 41
user108088 Avatar answered Oct 23 '22 11:10

user108088