# Python 中的三种拷贝方式

• 赋值拷贝
• 深拷贝
• 浅拷贝

## 赋值拷贝

``````one = [1, 2, 3]
two = one
print(one, two)
two[0] = 0
print(one, two)

one = [[1], [2], [3]]
two = one
print(one, two)
two[0] = [0]
print(one, two)

one = [[1], [2], [3]]
two = one
print(one, two)
two[0][0] = 0
print(one, two)

'''
[1, 2, 3] [1, 2, 3]
[0, 2, 3] [0, 2, 3]
[[1], [2], [3]] [[1], [2], [3]]
[[0], [2], [3]] [[0], [2], [3]]
[[1], [2], [3]] [[1], [2], [3]]
[[0], [2], [3]] [[0], [2], [3]]
'''
``````

## 深拷贝

``````import copy

one = [1, 2, 3]
two = copy.deepcopy(one)
print(one, two)
two[0] = 0
print(one, two)

one = [[1], [2], [3]]
two = copy.deepcopy(one)
print(one, two)
two[0] = [0]
print(one, two)

one = [[1], [2], [3]]
two = copy.deepcopy(one)
print(one, two)
two[0][0] = 0
print(one, two)

'''
[1, 2, 3] [1, 2, 3]
[1, 2, 3] [0, 2, 3]
[[1], [2], [3]] [[1], [2], [3]]
[[1], [2], [3]] [[0], [2], [3]]
[[1], [2], [3]] [[1], [2], [3]]
[[1], [2], [3]] [[0], [2], [3]]
'''
``````

## 浅拷贝

``````one = [1, 2, 3]
two = one.copy()
print(one, two)
two[0] = 0
print(one, two)

one = [[1], [2], [3]]
two = one.copy()
print(one, two)
two[0] = [0]
print(one, two)

one = [[1], [2], [3]]
two = one.copy()
print(one, two)
two[0][0] = 0
print(one, two)

'''
[1, 2, 3] [1, 2, 3]
[1, 2, 3] [0, 2, 3]
[[1], [2], [3]] [[1], [2], [3]]
[[1], [2], [3]] [[0], [2], [3]]
[[1], [2], [3]] [[1], [2], [3]]
[[0], [2], [3]] [[0], [2], [3]]
'''
``````
``````
import copy

'''

'''
print('---赋值拷贝---')
one = [1, 2, 3]
two = one
print(one, two)
two[0] = 0
print(one, two)

one = [[1], [2], [3]]
two = one
print(one, two)
two[0] = [0]
print(one, two)

one = [[1], [2], [3]]
two = one
print(one, two)
two[0][0] = 0
print(one, two)

'''

'''
print('---深拷贝---')
one = [1, 2, 3]
two = copy.deepcopy(one)
print(one, two)
two[0] = 0
print(one, two)

one = [[1], [2], [3]]
two = copy.deepcopy(one)
print(one, two)
two[0] = [0]
print(one, two)

one = [[1], [2], [3]]
two = copy.deepcopy(one)
print(one, two)
two[0][0] = 0
print(one, two)

'''

'''
print('---浅拷贝---')
one = [1, 2, 3]
two = one.copy()
print(one, two)
two[0] = 0
print(one, two)

one = [[1], [2], [3]]
two = one.copy()
print(one, two)
two[0] = [0]
print(one, two)

one = [[1], [2], [3]]
two = one.copy()
print(one, two)
two[0][0] = 0
print(one, two)

``````