注意:浅拷贝拷贝的只是原对象中每个元素的引用,然后将引用存在在一个新的列表中与索引进行绑定,并不意味着浅拷贝之后的列表地址与原列表相同;
1.浅拷贝
为什么更改不可变类型,不会同步更新?
所谓不可变就是说, 我们不能改变这个数据在内存中的值, 所以当我们改变这个变量的赋值时, 只是在内存中重新开辟了一块空间, 将这一条新的数据存放在这一个新的内存地址里, 而原来的那个变量就不在引用原数据的内存地址而转为引用新数据的内存地址了.
所以实际上并没有更改原内存的值
1.浅拷贝的缺陷:
浅拷贝会将列表中的内存地址全部复制一份到新列表;
如果更改了原列表中的不可变类型,由于是不可变,因此会重新申请内存,原列表内存地址也会变化,不会影响到新列表;
如果是可变类型,更改内部值,但是列表本身的内存地址没有发生变化,而新列表中该元素的内存地址和老列表中是一样的,因此新列表中的值也会发生改变;
2.切片也属于浅拷贝
3.用深拷贝让两个列表独立