深copy和浅copy

深copy:不仅copy变量的指针,还copy指针指向的数据

这里需要提到一个新名词,指针:变量和内存中数据的一种引用关系。变量通过指针对应到内存中的数据

在列表、元组、字典、集合中可以使用深copy

list=[1,2,3];

copy的作用是将列表拷贝出一份

newlist=list.copy();>>>print(list);[1,2,3]>>>print(newlist);[1,2,3]

如果修改newlist中的某一个元素,不会影响到list列表中本来的的元素(深copy)

>>>newlist[2]='hehe';>>>print(list)[1,2,3]>>>print(newlist)[1,2,hehe]

浅copy:只copy了指针(一份内存的引用),而在内存中保存的数据,还是仅仅只有一份


在列表、元组、字典出现copy操作的时候会发生浅copy

>>>lists=[[1,2,3],3,4];>>>newlists=lists.copy();>>>print(newlists)[[1,2,3],3,4]

改变newlists中元素的时候,如果修改,那么会影响到lists

>>>newlists[0][2]='hiahia';>>>print(lists)>>>[[1, 2, 'hiahia'], 3, 4]>>>print(newlists)>>>[[1, 2, 'hiahia'], 3, 4]