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.

4
  • When you do Myarray = [[0]*3]*3, you're actually multiplying the references. List comprehension is a one-line way to do it. Commented Nov 9, 2012 at 0:03
  • How much shorter would this be in other languages? Commented Nov 9, 2012 at 0:04
  • I like [x[:] for x in [[0]*3]*3] for non-numpy 2D arrays but I'm in the minority on that one. Commented Nov 9, 2012 at 0: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. Commented Nov 9, 2012 at 0:24

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Better yet: [[0]*3 for x in range(3)]
Both the answer above and Scotts work just fine and I thank you both. For the purpose of A level Junuxx is more readable so gets the vote!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.