python copy of the list six methods

The following is a list of six kinds of copy mode, in conclusion, there are three principles at the time of reproduction, which l 1 l1 a, l 6 l6 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, l 1 l1 replication principle is to l l The address also be copied later, that is, when l l When changed, l 1 l1 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 l l When changes are made to the internal sub-list, only l 6 l6 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:

  • l 1 = l l1 = l : When l l When changes l 1 l1 will change.
  • l 2 = l . c The p Y ( ) l2 = l.copy() l 3 = l [ : ] l3 = l [:] l 4 = l i s t ( l ) l4 = list(l) l 5 = c o p y . c o p y ( l ) l5 = copy.copy(l) :当 l l when a single change in the number, l 2 l2 , l 3 l3 , l 4 l4 , l 5 l5 does not change; when l l sublist changes, l 2 l2 , l 3 l3 , l 4 l4 , l 5 l5 will change.
  • l 6 = c o p y . d e e p c o p y ( l ) l6 = copy.deepcopy(l) : Whether l l how change, l 6 l6 do not change.
Published 135 original articles · won praise 30 · Views 100,000 +

Guess you like

Origin blog.csdn.net/qq_36758914/article/details/105269814