The following is a list of six kinds of copy mode, in conclusion, there are three principles at the time of reproduction, which a, is the second, the third part of the other four methods.
import copy
l = [1, 2, [3, 4]]
l1 = l
l2 = l.copy()
l3 = l[:]
l4 = list(l)
l5 = copy.copy(l)
l6 = copy.deepcopy(l)
We can start to print their addresses:
print(id(l))
print(id(l1))
print(id(l2))
print(id(l3))
print(id(l4))
print(id(l5))
print(id(l6))
2515754890952
2515754890952
2515754891912
2515754910792
2515754891208
2515754863048
2515754910984
It can be seen, replication principle is to The address also be copied later, that is, when When changed, will change. But other means of copying this problem does not occur, such as:
l[0] = 0
print('l: ', l)
print('l1: ', l1)
print('l2: ', l2)
print('l3: ', l3)
print('l4: ', l4)
print('l5: ', l5)
print('l6: ', l6)
get:
l: [0, 2, [3, 4]]
l1: [0, 2, [3, 4]]
l2: [1, 2, [3, 4]]
l3: [1, 2, [3, 4]]
l4: [1, 2, [3, 4]]
l5: [1, 2, [3, 4]]
l6: [1, 2, [3, 4]]
But if we for When changes are made to the internal sub-list, only will remain the same, such as:
import copy
l = [1, 2, [3, 4]]
l1 = l
l2 = l.copy()
l3 = l[:]
l4 = list(l)
l5 = copy.copy(l)
l6 = copy.deepcopy(l)
l[2][0] = 0
print('l: ', l)
print('l1: ', l1)
print('l2: ', l2)
print('l3: ', l3)
print('l4: ', l4)
print('l5: ', l5)
print('l6: ', l6)
l: [1, 2, [0, 4]]
l1: [1, 2, [0, 4]]
l2: [1, 2, [0, 4]]
l3: [1, 2, [0, 4]]
l4: [1, 2, [0, 4]]
l5: [1, 2, [0, 4]]
l6: [1, 2, [3, 4]]
So, conclusion:
- : When When changes will change.
- 、 、 、 :当 when a single change in the number, , , , does not change; when sublist changes, , , , will change.
- : Whether how change, do not change.