Home  >  Article  >  Backend Development  >  A simple explanation of deep and shallow copying in python (with code)

A simple explanation of deep and shallow copying in python (with code)

不言
不言forward
2018-10-27 16:03:551955browse

This article brings you a simple explanation of deep and shallow copying in Python (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Review, copy in depth.

Above code:

# -*- coding: utf-8 -*-
"""
Created on Thu Sep 20 14:18:48 2018

@author: Lenovo
"""

import copy,json

a={"ab":1,"cd":{"ef":2},"gh":[1,2,3]}
print "a1:",a

b=dict(a["cd"])
c=copy.copy(a)
d=copy.deepcopy(a)
e=a["cd"]
a["cd"]["xy"]=3
a["fx"]=5
a["cd"]["ef"]=20
print "a2:",a
print "b :",b
print "c :",c
print "d :",d
print "e :",e

Result:

a1: {'gh': [1, 2, 3], 'ab': 1, 'cd': {'ef': 2}}
a2: {'gh': [1, 2, 3], 'fx': 5, 'ab': 1, 'cd': {'xy': 3, 'ef': 20}}
b : {'ef': 2}
c : {'cd': {'xy': 3, 'ef': 20}, 'ab': 1, 'gh': [1, 2, 3]}
d : {'cd': {'ef': 2}, 'ab': 1, 'gh': [1, 2, 3]}
e : {'xy': 3, 'ef': 20}

It can be seen from the result:

dict() command creates a new dictionary;

"="Assignment is equivalent to using the concept of "reference";

copy.copy is a shallow copy. Modifications to the copied information will be modified accordingly, adding or adding other uncopied information. Modification, shallow copy object will not be modified;

For example, the scope of c copy is "gh", "ab", "cd" three keys, if the value of these three keys is modified, after copying The object will be modified accordingly, but if other information is modified, such as adding key "fx", the copied object will not be modified.

copy.deepcopy is a deep copy, creating a brand new object.

The above is the detailed content of A simple explanation of deep and shallow copying in python (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete