python - Abnormal list behaviour -
i working on problem , came across this.
python code
row=[] col=[] init=[-1,-1] now append init row , col.
row.append(init) row.append(init) col.append(init) col.append(init) therefore row = [[-1,-1],[-1,-1]] , col = [[-1,-1],[-1,-1]]
now when alter init[0] = 9 row , col becomes row = [[9,-1],[9,-1]] , col = [[9,-1],[9,-1]]
this happens because store same reference object init on , over. when modify object sees it.
you seek appending copies of list instead. 1 way illustration be:
row.append(list(init)) there's more 1 way clone list.
python
No comments:
Post a Comment