-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]]
2
  • 1
    How are you puzzled by this behaviour? Commented Nov 29, 2020 at 17:06
  • May be I am losing my mind. I wanted to assign (0,0)-th element to 0, (1,0)-th element to 1, (2,0)-th element to 2, ... Commented Nov 29, 2020 at 17:08

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.