-1

I just started learning python. I come from C++/Java background. To understand two dimensional arrays. I have written the following snippet

x = [[0]*3]*3
for i in range(0,3):
   for j in range(0,3):
      x[i][j] = i+j

for i in range(0,3):
   for j in range(0,3):
      print x[i][j],
   print ""

Why is this program printing

2 3 4
2 3 4
2 3 4

instead of my expectation

0 1 2
1 2 3
2 3 4

I thought about the reason for this and I am not able to conclude anything. Is this something to do with reference variables?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Ravi Chandra
  • 677
  • 12
  • 24

2 Answers2

5

Let us walk through the first statement

>>> x = [0]
>>> id(x)
139705127800200
>>> id(x[0])
40157552

Note down this id 40157552. Now when we multiply it by 3. You can see the addresses of the others

>>> y = x*3
>>> for i in y:
...     print id(i)
... 
40157552
40157552
40157552
>>> y
[0, 0, 0]

All have the same id 40157552. So this is the reason of your failure to get the correct output.

You can create 2d arrays like already mentioned or you can try the module numpy by

numpy.zeros((3,3)).

This creates the exact array you want.

Now for a small demo

x = [[0 for i in range(3)] for j in range(3)]
for i in range(0,3):
   for j in range(0,3):
      x[i][j] = i+j

for i in range(0,3):
   for j in range(0,3):
      print x[i][j],
   print ""

This will print

0 1 2 
1 2 3 
2 3 4 

as expected.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
4

You shouldn't create a 3d array with multiple it on 3 , because actually you crate 3 reference to one object . instead use the following :

x = [[0 for i in range(3)] for j in range(3)]
Mazdak
  • 105,000
  • 18
  • 159
  • 188