First , We know Python There is 6 Standard data types , They are divided into changeable and immutable .
immutable :Number( Numbers )、String( character string )、Tuple( Tuples ).
Can change :List( list )、Dictionary( Dictionaries )、Set( aggregate ).
Change the value of the variable type element in the original object , It will also affect the copied objects .
Change the value of immutable elements in the original object , No copy objects .
Code demonstration
import copy# Define a list , The first element is a mutable type .list1 = [[1,2], 'fei', 66];# Carry out shallow copylist2 = copy.copy(list1);# Whether the object address is the same .print(id(list1));print(id(list2));# result : Different 4617781646177936# Whether the address of the first element is the same .print(id(list1[0]));print(id(list2[0]));# result : identical 4624043246240432# Whether the address of the second element is the same .print(id(list1[1]));print(id(list2[1]));# result : identical 4554732845547328# Change the first value , View the changes of the copied object .list1[0][0] = 2;print(list2);# result : Copy object changes [[2, 2], 'fei', 66]# Change the second value , View the changes of the copied object .list1[1] = 'ge';print(list2);# result : The copied object has not changed [[2, 2], 'fei', 66]
Deep copy Deep copy , Except for top-level copy , The child elements are also copied .
After deep copy , All of the original and copy objects Variable elements There is no same address .
Code demonstration
import copy# Define a list , The first element is a mutable type .list1 = [[1,2], 'fei', 66];# Proceed deep copylist2 = copy.deepcopy(list1);# Whether the object address is the same .print(id(list1));print(id(list2));# result : Different 4617781646177936# Whether the address of the first element is the same .print(id(list1[0]));print(id(list2[0]));# result : Different 4912385649588784# Whether the address of the second element is the same .print(id(list1[1]));print(id(list2[1]));# result : identical 4554732845547328# Change the first value , View the changes of the copied object .list1[0][0] = 2;print(list2);# result : The copied object has not changed [[1, 2], 'fei', 66]# Change the second value , View the changes of the copied object .list1[1] = 'ge';print(list2);# result : The copied object has not changed [[1, 2], 'fei', 66]
This is about Python This is the end of the articles on medium and deep copy and shallow copy . I hope it will be helpful for your study , I also hope you can support the software development network .