开发者

Problem with lists' dependence (python)

I'm sure this question was answered thousands time before, but English is not my native language and I am really bad at searching so I beg your pardon. I am trying to learn python by writing a database for my job, so I met this issue. Simplified peace of code:

    x=[[0,0],[0,0]]
    y=x[0:]
    y[0][0]="1"
    print x

and the output:

    [['1', 0], [0, 0]]

I underst开发者_开发百科and I'm missing something fundamental here, but why "x" was changed along with "y"?. All answers will be much appreciated.


Using x[0:] does not create a 'deep copy'; it is essentially copying the references to the inner arrays, or a 'shallow copy', such that setting y[0] or y[1] would not change x, but setting the inner array's items would.


y=x[0:] 

This does copy the list x but the since the elements of x are arrays these will be copied as references. What you need is to copy each element of x. For example:

y = [val[:] for val in x]

Then changing y won't affect x.

Edit:

Another alternative that works for a wider area of cases is like it was suggested deepcopy. So:

from copy import deepcopy

y = deepcopy(x)

This will work for nested list and non iterable elements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜