Python learning road 7 - deep and shallow copy analysis

 1. Object assignment

  Create a list variable Alex, the variable contains a sublist, and assign a value to the variable lzl through the variable Alex.

  Then modify the elements of the variable Alex, what will happen to lzl at this time? Let's analyze the changes of both by memory address.

1  #Object    assignment 
2  import copy                      # import calls the copy module 
3   
4 Alex = [ " Alex " , 28, [ " Python " , " C# " , " JavaScript " ]]
 5 lzl = Alex                        # Direct assignment 
6   
7  #    Print before modification 
8  print (id(Alex)) #Print the address of the list in memory
 9  print (Alex) #Print the content of the list
 10  print ([id(adr)for adr in Alex]) #Print the address 11 of each element in the list (including sublists) in memory
 #Output : 7316664 12 #         ['Alex', 28, ['Python', 'C#', 'JavaScript'] ] 13 #         [2775776, 1398430400, 7318024] 14 print (id(lzl))
 15 print (lzl)
 16 print ([id(adr) for adr in lzl])
 17 #Output : 7316664 18 #         ['Alex', 28 , ['Python', 'C#', 'JavaScript']] 19 #         [2775776, 1398430400,7318024] 20 21 #Modify     the variable 
 
 
    
 
 
  
 
22 Alex[0]='Mr.Wu'
23 Alex[2].append('CSS')
24 print(id(Alex))
25 print(Alex)
26 print([id(adr) for adr in Alex])
27 # 输出:  7316664
28 #        ['Mr.Wu', 28, ['Python', 'C#', 'JavaScript', 'CSS']]
29 #        [5170528, 1398430400, 7318024]
30 print(id(lzl))
31 print(lzl)
32 print([id(adr) for adr in lzl])
 33  #Output : 7316664 
34  #         ['Mr.Wu', 28, ['Python', 'C#', 'JavaScript', 'CSS']] 
35  #         [5170528, 1398430400, 7318024]

 

  

 

Guess you like

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