How can I assign by value in python

前端 未结 2 1374
没有蜡笔的小新
没有蜡笔的小新 2021-01-23 01:50

I understand that, due to the way Python works x = []; y = x; x.append(1); y will print [1]. However, the reverse, say,

z = [1,2]
temp          


        
2条回答
  •  情话喂你
    2021-01-23 02:30

    Why not make temp a copy of z:

    >>> z = [1, 2]
    >>> temp = z[:]
    >>> temp[1] = 3
    >>> z
    [1, 2]
    >>> temp
    [1, 3]
    >>>
    

    [:] easily makes a shallow copy of a list.

    However, you might also be interested in copy.copy and copy.deepcopy, both of which come from Python's copy module.

提交回复
热议问题