Sagar Rakshe
Sagar Rakshe

Reputation: 2830

Abnormal list behaviour

I was working on some problem and came across this.

Python code

row=[]
col=[]
init=[-1,-1]

Now I append this init to row and col.

row.append(init)
row.append(init)

col.append(init)
col.append(init)

Therefore row = [[-1,-1],[-1,-1]] and col = [[-1,-1],[-1,-1]]

Now when i change init[0] = 9 my row and col becomes row = [[9,-1],[9,-1]] and col = [[9,-1],[9,-1]]

Upvotes: 1

Views: 145

Answers (2)

cnicutar
cnicutar

Reputation: 182619

This happens because you store the same reference to the object init over and over. So when you modify the object everyone sees it.

You could try appending copies of the list instead. One way for example could be:

row.append(list(init))

There's more than one way to clone a list.

Upvotes: 6

Related Questions