1

I have the following simple python code:

arr1 = [[0]*4]*4

arr = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]

print arr
print arr1
print arr1 == arr

for x in range(0,3):
    arr[1][1] = 1 

for x in range(0,3):
    arr1[1][1] = 1 

print arr
print arr1
print arr == arr1

This code produces the following output:

[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
True
[[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
[[0, 1, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0]]
False

Could someone tell me why the output is different and why the arrays aren't equal anymore? I am doing the same operation on the arrays and they are equal in the beginning as shown by the output. Please let me know if I am doing something stupid here.

user2731223
  • 114
  • 8
  • 1
    For `arr1`, you have a list of the same object 4 times. Change one, you change them all. `arr` is a list of 4 distinct objects (though they evaluate to be the same). Change one, the others remain the same. You can find examples of this throughout SO. – busybear Oct 04 '18 at 21:42
  • Thanks for pointing out it was a duplicate. – user2731223 Oct 04 '18 at 21:43

0 Answers0