One, depth copy
See Copy day19-1.py
S=[1, ' Zhangsan ', ' Lisi '] #s2是s的拷贝s2 =s.copy () #打印s2和s是一样的print (S2) #修改s2s2 [0]=2# print S is the unchanged print (s) #打印s2因为修改了所以有变化print (S2) [1, ' Zhangsan ', ' Lisi '] [1, ' Zhangsan ', ' Lisi '] [2, ' Zhangsan ', ' Lisi ']
If the modified element is a list, the source list also changes day19-2.py
s = [[up], ' Zhangsan ', ' Lisi ']s3=s.copy () print (S3) print (s) s3[0][1]=3# modify S3 inside list element after source list also corresponds to change print (S3) print (s) [[1, 2] , ' Zhangsan ', ' Lisi '][[1, 2], ' Zhangsan ', ' Lisi '][[1, 3], ' Zhangsan ', ' Lisi '][[1, 3], ' Zhangsan ', ' Lisi ']
Why so, because the first modification of an immutable element corresponding to the pointer has changed, the second S and S3 point to the memory address is a variable element (list) When the list changes, but the list of memory address does not change the direction of S and S3 did not change, So modifying the first element list of S3 corresponding to the first element list of S is also changed.
This is the shallow copy, the shallow copy only copies the first layer.
Python full stack day19 (function supplement)