1. Lists and dictionaries, directly assigned, are shallow copies, where both sides point to the same address, because Python passes by reference to mutable objects.
>>> a = [1, 2, 3]>>> B =a>>>b[1, 2, 3]>>> A[0] ='Apple'>>>a['Apple', 2, 3]>>>b['Apple', 2, 3]>>> >>> >>> dic = {'a':'Apple','b':'Banbana'}>>> Dic2 =DiC>>>dic2{'a':'Apple','b':'Banbana'}>>> dic['b'] ='Blueberry'>>>dic{'a':'Apple','b':'Blueberry'}>>>dic2{'a':'Apple','b':'Blueberry'}
2. For a non-nested list, use a full slice [:], the factory function list (), or copy.copy () are deep copies.
>>> A = [1, 2, 3 >>> b = >>> c = a[:] >>> import copy >>> d = Copy.copy (a) > >> >>> a[0] = ' >>>
3. For non-nested dictionaries, use the Factory function Dict (), or copy.copy () are deep copies.
>>> dic = {'a':'Apple','b':'Banana'}>>> Dic2 =dict (DIC)>>>ImportCopy>>> DIC3 =copy.copy (DIC)>>> >>> dic['b'] ='Blueberry'>>>dic{'a':'Apple','b':'Blueberry'}>>>dic2{'a':'Apple','b':'Banana'}>>>dic3{'a':'Apple','b':'Banana'}
4. For nested lists, nested dictionaries can only use copy.deepcopy () to implement deep copies.
>>>ImportCopy>>> >>> A = [1, 2, ['Apple']]>>> B =Copy.deepcopy (a)>>> A[2][0] ='Watermelon'>>>a[1, 2, ['Watermelon']]>>>b[1, 2, ['Apple']]>>> >>> >>> dic = {'a':'Apple','b': {'B1':'Banana','B2':'Blueberry'}}>>> Dic2 =copy.deepcopy (DIC)>>> dic['b']['B1'] ='Bukeneng'>>>dic{'a':'Apple','b': {'B1':'Bukeneng','B2':'Blueberry'}}>>>dic2{'a':'Apple','b': {'B1':'Banana','B2':'Blueberry'}}
5. For tuples that Nest mutable objects, only copy.deepcopy () implements a deep copy.
>>>ImportCopy
>>>>>> T = (1, 2, ['Apple'])>>> t2 =T>>> t3 =tuple (t)>>> T4 =copy.copy (t)>>> T5 =copy.deepcopy (t)>>> >>> T[2][0] ='Watermelon'>>>T (1, 2, ['Watermelon'])>>>T2 (1, 2, ['Watermelon'])>>>T3 (1, 2, ['Watermelon'])>>>T4 (1, 2, ['Watermelon'])>>>T5 (1, 2, ['Apple'])
Finish.
Shallow and deep copies in Python