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

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

不言
Release: 2018-10-27 16:03:55
forward
2024 people have browsed it

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
Copy after login

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}
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template