How can I assign by value in python

前端 未结 2 1370
没有蜡笔的小新
没有蜡笔的小新 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:24

    Copying a list is easy ... Just slice it:

    temp = z[:]
    

    This will create a shallow copy -- mutations to elements in the list will show up in the elements in z, but not changes to temp directly.


    For more general purposes, python has a copy module that you can use:

    temp = copy.copy(z)
    

    Or, possibly:

    temp = copy.deepcopy(z)
    

提交回复
热议问题