0

Suppose I have this code:

dim = 3
eye =  [[0] * dim] * dim

and it is a list of list, I checked

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

Now, if I do this, I get:

eye[1][2] = 1
eye
[[0, 0, 1], [0, 0, 1], [0, 0, 1]]

However, if I manually put in this expression, the above code works as expected:

eye2=[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
eye2[1][2] = 1
eye2
[[0, 0, 0], [0, 0, 1], [0, 0, 0]]

What is the difference between the two ?

Update: Thanks for all the explanations, suppose I have this code:

a = [0]
type(a)
b = a * 3  # or b = [[0] *3]

So, b holds the 3 references to a. And I expect changing b[0] or b[1] or b[2] will change all 3 elements.
But this code shows the normal behavior, why is that ?

b[1] = 3
b
[0, 3, 0]
user1502776
  • 553
  • 7
  • 17
  • Someone taught me that I can do that kind of scalar multiplication to lists. If it turns out so weird, what is the application of this method ? – user1502776 Oct 28 '14 at 06:17

3 Answers3

1

Any array entry is as a label of memory address and when you multiple it with a variable actually you create a pointer to 3 palace in your array ! you can figure it out with a list comprehension as below :

Matrix = [[0 for x in xrange(3)] for x in xrange(3)]
Mazdak
  • 105,000
  • 18
  • 159
  • 188
0
dim = 3
eye =  [[0] * dim] * dim

its make the copy of same, of if you change at one place it will be reflected to all

Hackaholic
  • 19,069
  • 5
  • 54
  • 72
0
dim = 3
eye =  [[0] * dim] * dim
print id(eye[0])
print id(eye[1])
print id(eye[2])

Ouput:-

139834251065392
139834251065392
139834251065392

So when you are doing eye = [[0] * dim] * dim it actually refrencing refrencing three list to same object that is eye.

while in other case

eye2=[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
print id(eye2[1])
print id(eye2[2])
print id(eye2[0])

ouput:-

139863345170480
139863260058256
139863260067240

Here everytime refrence id is diffrent.

Vishnu Upadhyay
  • 5,043
  • 1
  • 13
  • 24