The difference between the python and shallow copy of the deep copy

First, the assignment

alist = ["a","b","c",[5,6],10]
aa = alist
alist.append("yu")
aa.append("iop")
alist[3].append(99)
alist[3].append("test")
print(alist)
print(aa)

Execution results are as follows:

['a', 'b', 'c', [5, 6, 99, 'test'], 10, 'yu', 'iop']
['a', 'b', 'c', [5, 6, 99, 'test'], 10, 'yu', 'iop']

Assignment instructions are passed between two mutually variable data, modify the value of any variable, other variables will impact on the value for

 

Second, the shallow copy, Copy ()

import copy

# Shallow copy, no copies of the internal elements of the element, has inner elements will affect each other to change the

blist = ["a","b","c",[5,6],10]
bb = copy.copy(blist)
blist.append("haha")
bb.append(89)

blist[3].append("qe")
bb[3].append(99)

print(blist)
print(bb)

Results of the:

[90, 'b', ' c', [5, 6, 'qe', 99], 10, 'haha'] # blist additional 'haha', and not the value bb, the number of internal elements for blist [ 3] was added 'qe', will be applied to the bb bb [3] the internal elements
[ 'a', 'b' , 'c', [5, 6, 'qe', 99], 10, 89] #bb added 89, not blist value, the number of internal elements BB [3] add 99, will act to blist blist [3] the internal element

Third, the deep copy

import copy

# Deep copy, the copy of each element independently of each other changes, including sub-elements
clist = [ "A", "B", "C", [5,6], 10]
CC = copy.deepcopy (clist)
clist .append (90)
cc.append (100)

clist[3].append(11)
cc[3].append(10)

print(clist)
print(cc)

Results of the:

['a', 'b', 'c', [5, 6, 11], 10, 90]
['a', 'b', 'c', [5, 6, 10], 10, 100]

In fact, the deep copy, all of the outer element is copied, the deep copy, change the values ​​of two variables, will not affect each other

 

Guess you like

Origin www.cnblogs.com/banxiade/p/12470241.html