Reputation: 2830
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
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 append
ing 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
Reputation: 11
This may be of help explaining why
http://www.jeffknupp.com/blog/2012/11/13/is-python-callbyvalue-or-callbyreference-neither/
Upvotes: 1