程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Differences between deep copy and shallow copy in Python

編輯:Python

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 ).

Shallow copy

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 .



  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved