First, we need to make it clear that the list's shading is for nested lists , which means that we only need to consider this problem for nested lists. See examples.
list1=['boss','Dick',['Old Three','Old Four','Old Five'],'Old Six','Lao Qi']list2=list1.copy ()Print(List1,'\ n', List2)#print a list of twoPrint(ID (list1),'\ n', ID (LIST2))#Print the address of a two listPrint(ID (list1[2]),'\ n', ID (list2[2]))#Print the address of two nested lists
Run results
['boss','Dick', ['Old Three','Old Four','Old Five'],'Old Six','Lao Qi'] ['boss','Dick', ['Old Three','Old Four','Old Five'],'Old Six','Lao Qi']3072878348 30725616443072841164 3072841164
As can be seen from the results, although List1 and LIAT2 have the same address, but nested lists [' old three ', ' old four ', ' old five '] have the same address. This is a shallow copy. If we modify the value of the nested list at this time. Two lists will change. Look at the code below.
list1[2][1]=' hahaha 'print(list1,'\ n', List2)
Run results
['boss','Dick', ['Old Three','ha ha haha','Old Five'],'Old Six','Lao Qi'] ['boss','Dick', ['Old Three','ha ha haha','Old Five'],'Old Six','Lao Qi']
In fact, the principle is very simple, the middle of the nested list is actually allocated space alone, and then List1 and List2 are to refer to the address, so when its value changes, two lists are changed.
Deep copy
The copy module needs to be used for deep replication to see examples.
ImportCopylist1=['boss','Dick',['Old Three','Old Four','Old Five'],'Old Six','Lao Qi']list2=copy.deepcopy (List1)Print(List1,'\ n', List2)#print a list of twoPrint(ID (list1),'\ n', ID (LIST2))#Print the address of a two listPrint(ID (list1[2]),'\ n', ID (list2[2]))#Print the address of two nested lists
Results
['boss','Dick', ['Old Three','Old Four','Old Five'],'Old Six','Lao Qi'] ['boss','Dick', ['Old Three','Old Four','Old Five'],'Old Six','Lao Qi']3071562732 30719289403071600076 3071600108
This is what happens to two lists if we modify the values of nested lists.
list1[2][1]=' hahaha 'print(list1,'\ n', List2)
Results
['boss','Dick', ['Old Three','ha ha haha','Old Five'],'Old Six','Lao Qi'] ['boss','Dick', ['Old Three','Old Four','Old Five'],'Old Six','Lao Qi']
Python Basics (v): A list of shades of copy