import copy
a = [1, 2, 3, 4, [45, 67]]
b = a[:]
c = list(a)
d = copy.copy(a)
e = a
h = [1, 2, 3, 4, [45, 67]]
k = copy.deepcopy(a)
a.append(5)
a [1, 2, 3, 4, [45, 67], 5]
b [1, 2, 3, 4, [45, 67]]
c [1, 2, 3, 4, [45, 67]]
d [1, 2, 3, 4, [45, 67]]
e [1, 2, 3, 4, [45, 67], 5]
h [1, 2, 3, 4]
k [1, 2, 3, 4, [45, 67]]
对于 a来说,b,c,d都相当于它的浅拷贝; e相当于直接赋值,相当于a的别名;h只是值和a相等,k深拷贝。
上面这些只有e与a的id是相同的,其他不论哪一个与a的id都是不同的,但a append时,也只有e跟着变化,
所以说浅拷贝对于父对象来说也是完完全全的拷贝,开辟新的内存地址
import copy
a = [1, 2, 3, 4, [45, 67], (11, 44)]
b = a[:]
c = list(a)
d = copy.copy(a)
e = a
h = [1, 2, 3, 4, [45, 67], (11, 44)]
k = copy.deepcopy(a)
a.append(5)
a[4] += [11, 33]
a[5] += (66,)
a [1, 2, 3, 4, [45, 67, 11, 33], (11, 44, 66), 5]
b [1, 2, 3, 4, [45, 67, 11, 33], (11, 44)]
c [1, 2, 3, 4, [45, 67, 11, 33], (11, 44)]
d [1, 2, 3, 4, [45, 67, 11, 33], (11, 44)]
e [1, 2, 3, 4, [45, 67, 11, 33], (11, 44, 66), 5]
h [1, 2, 3, 4, [45, 67], (11, 44)]
k [1, 2, 3, 4, [45, 67], (11, 44)]
相对于上面的例子,又在a中加了元组,
又在a的子对象中的列表添加,发现与之相关的浅拷贝和别名全部改变,而对于元组的添加,只有别名跟着变,浅拷贝们不变。
别名跟着变很好理解。浅拷贝的列表能做到的只是复制父对象,对于里面的子对象却无能为力了,对于里面的子对象只能做到复制索引。
元组是不可变对象, 复制的不是索引地址。
import copy
a = {"q": "2", "q2": [1, 2, 4]}
c = copy.copy(a)
d = copy.deepcopy(a)
print(id(a["q2"]))
print(id(c["q2"]))
print(id(d["q2"]))
# 2153344495176
# 2153344495176
# 2153344494152
t1 = (1, 2, 3)
t2 = tuple(t1)
print(t2 is t1)
# True
t3 = t1[:]
print(t3 is t1)
# True
t4 = t1
print(t4 is t1)
# True
l1 = [1, 2, 3]
l2 = l1[:]
print(l1 is l2)
# False
这说明对元组操作 [:] 不是创建副本, 而是复制了引用: 对于列表来说[:], 是重新开辟内存