-1

i am puzzled by this behavior

r,c = (5,2)
slist = [[0]*c]*r
print(slist)

for i in range(r):
    slist[i][0] = i
print(slist)

Output is

[[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]]
[[4, 0], [4, 0], [4, 0], [4, 0], [4, 0]]
gsakthivel
  • 365
  • 3
  • 17

1 Answers1

3

When you do [[0] * c] * r, you create a list where every element is a reference to the same list. So, when you change one, they all change. Use a list comprehension with a range instead to create unique lists:

slist = [[0] * c for _ in range(r)]

See here for more info.

Aplet123
  • 33,825
  • 1
  • 29
  • 55