Possible duplicate:
How to initialize a two-dimensional array in Python?
When solving a simple two-dimensional array problem, I found a solution on this site that explained how to declare it in Python using the overload operator.
Example:
Myarray = [[0]*3]*3
this will create the following array (list)
[[0,0,0],[0,0,0],[0,0,0]]
This seems great until you use it:
if you assign an element, for example:
Myarray [0][0] = 1
you will get unexpected output:
[[1,0, 0],[1,0,0] , [1,0,0]]
Actually assigning Myarray [1] [0] and Myarray [2] [0] at the same time
My decision:
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 an easier way ? This was a solution to the Cambridge level A question, and seems too long for students compared to other languages.