4

Possible Duplicate:
How to initialize a two-dimensional array in Python?

In solving a simple problem regarding a two dimensional array I came across a solution on this site that explained how to declare one in Python using the overload operator.

Example:

Myarray = [[0]*3]*3

this would produce the following array (list)

[[0,0,0],[0,0,0],[0,0,0]]

This seems fine until you use it:

if you assign an element for example:

Myarray [0][0] = 1

you get the unexpected output:

[[1,0, 0],[1,0,0] , [1,0,0]]

In effect assigning Myarray [1][0] and Myarray[2][0] at the same time

My solution:

Myarray = [[][][]]
for i in range(0,3):
  for j in range (0,3):
     Myarray[i].append(0)

This solution works as intended:

Marray[0][1] = 1

gives you

[[1,0, 0],[0,0,0] , [0,0,0]]

Is there a simpler way to do this? This was a solution to an A level Cambridge question and seems too long winded for students compared to other languages.

Community
  • 1
  • 1
Timothy Lawman
  • 2,194
  • 6
  • 24
  • 33
  • When you do `Myarray = [[0]*3]*3`, you're actually multiplying the references. List comprehension is a one-line way to do it. – Makoto Nov 09 '12 at 00:03
  • How much shorter would this be in other languages? – Scott Hunter Nov 09 '12 at 00:04
  • I like `[x[:] for x in [[0]*3]*3]` for non-numpy 2D arrays but I'm in the minority on that one. – DSM Nov 09 '12 at 00:05
  • @ScottHunter: There are a few Python-like languages where it _is_ just `[[0]*3]*3`, because they don't do references right. Of course staying in Python, assuming you've done `from numpy import *`: `zeros((3,3))` is actually shorter, as well as better. – abarnert Nov 09 '12 at 00:24

1 Answers1

6

With vanilla Python, you could use this, a nested list comprehension

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

Unlike the multiplied list you showed in your example, it has the desired behavior

>>> m[1][0] = 99
>>> m
[[0, 0, 0], [99, 0, 0], [0, 0, 0]]

However, for serious use of multidimensional arrays and/or numerical programming, I'd suggest you use Numpy arrays.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Junuxx
  • 14,011
  • 5
  • 41
  • 71