# Python对象的深浅拷贝，你到底变不变

• == 比较对象之间的值是否相等
• is 比较的是对象身份是否相等，它们是否同一个对象

我们一般通过id来是否相等来判断是否同一个对象

``````a = 10
b = 10

a == b
True

id(a)
4427562448

id(b)
4427562448

a is b
True``````

``````a = 257
b = 257

a == b
True

id(a)
4473417552

id(b)
4473417584

a is b
False``````

``````l1 = [1, 2, 3]
l2 = list(l1)

l2
[1, 2, 3]

l1 == l2
True

l1 is l2
False

s1 = set([1, 2, 3])
s2 = set(s1)

s2
{1, 2, 3}

s1 == s2
True

s1 is s2
False``````

``````import copy
l1 = [1, 2, 3]
l2 = copy.copy(l1)
t1 = (1, 2, 3)
t2 = tuple(t1)

t1 == t2
True

t1 is t2
True``````

``````l1 = [[1, 2], (30, 40)]
l2 = list(l1)

l2
[[1, 2], (30, 40)]

l1.append(100)
l1[0].append(3)

l1
[[1, 2, 3], (30, 40), 100]

l2
[[1, 2, 3], (30, 40)]``````

l2竟然变了，这是为什么。首先初始化一个列表l1，里面的元素是一个列表和元组，然后对l1执行浅拷贝，赋予了l2 ，但是l2中的元素和l1指向同一个列表和元组对象，只有列表对象变，你浅拷贝就要跟着我变。

l1.append(100)l1的列表新增元素100，不会对l2产生影响，l1和l2是两个不同的对象

``````l1[1] += (50, 60)

l1
[[1, 2, 3], (30, 40, 50, 60), 100]

l2
[[1, 2, 3], (30, 40)]``````

### 深度拷贝

``````import copy
l1 = [[1, 2], (30, 40)]
l2 = copy.deepcopy(l1)
l1.append(100)
l1[0].append(3)

l1
[[1, 2, 3], (30, 40), 100]

l2
[[1, 2], (30, 40)]``````

• 浅拷贝，不可变的不可变，可变的依旧可变
• 深拷贝，都不可变