python shallow copy & deep copy

x=[1,[2,3],4]
l=x[:]     #Copy x shallowly to y and z, that is, modifying 1 and 4 does not affect the value of l, but modifying the nesting [2,3], the nested value in l will also change
 x[ 0 ] = 11
 x[ 1 ][ 0 ]= 22
 print (l)     #[1, [22, 3], 4]
 print ( '******************** ********************' )
x=[1,[2,3],4]
l= list (x)     #Shallow copy x to y and z, that is, modifying 1 and 4 does not affect the value of l, but modifying the nesting [2,3], the value of the nesting in l will also change
 x[ 0 ] = 11
 x[ 1 ][ 0 ]= 22
 print (l)     #[1, [22, 3], 4]
 print ( '******************** ********************' )
x=[1,[2,3],4]
l=x.copy() #Shallow     copy x to y and z, that is, modifying 1 and 4 does not affect the value of l, but modifying the nesting [2,3], the value of the nesting in l will also change
 x[ 0 ]= 11
 x[ 1 ][ 0 ]= 22
 print (l)     #[1, [22, 3], 4]
 print ( '******************* *****************' )
 import copy
x=[1,[2,3],4]
l=copy.copy(x) #Shallow     copy x to y and z, that is, modifying 1 and 4 does not affect the value of l, but modifying the nesting [2,3], the value of the nesting in l will also change
 x[ 0 ]= 11
 x[ 1 ][ 0 ]= 22
 print (l)     #[1, [22, 3], 4]
 print ( '****************** ********************' )
x=[1,[2,3],4]
l=copy.deepcopy(x) #Deep     copy x to y and z, that is, modifying any value in x will not affect the value of l
 x[ 0 ]= 11
 x[ 1 ][ 0 ]= 22
 print ( l)     #[1, [2, 3], 4]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326000536&siteId=291194637