0

I create two same zero lists. Yet the results are different when the lists are assigned to same values. Here are my code and result.

code:

m1 = [[0] * 4] * 4
m2 = [[0 for j in range(4)] for i in range(4)]
m1[0][1] = 1
m2[0][1] = 1
print('m1:', m1)
print('m2:', m2)

result:

m1: [[0, 1, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0]]
m2: [[0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Or maybe the two lists are not the "same"? Any help would be appreciated.

cmjdxy
  • 396
  • 1
  • 2
  • 15

1 Answers1

0

In m1, you're referencing the same [[0] * 4] 4 times. Basically you're doing:

x = [0, 0, 0, 0]
m1 = [x, x, x, x]
x[1] = 1

resulting in x being [0 1 0 0] and being repeated 4 times in m1

pythomatic
  • 647
  • 4
  • 13