Home > Backend Development > Python Tutorial > The difference between deep and shallow copy in python

The difference between deep and shallow copy in python

爱喝马黛茶的安东尼
Release: 2022-06-08 14:09:22
Original
3593 people have browsed it

The assignment of objects in Python is actually a reference to the object. When an object is created and assigned to another variable, Python does not copy the object, only the reference to the object.

The difference between deep and shallow copy in python

#Shallow copy: The outermost object itself is copied, and the internal elements are just copied with a reference. That is, the object is copied once, but other objects referenced in the object are not copied

Deep copy: Both peripheral and internal elements copy the object itself, not the references. That is, the object is copied once, and other objects referenced in the object are also copied.

The role of deep and shallow copy

1. Reduce memory usage
2. In the future, when cleaning, modifying or storing data, Make a copy of the original data to prevent the original data from being found after the data is modified.

Related recommendations: "Python Video Tutorial"

Shallow copy (copy): Copies the parent object and does not copy the internal child objects of the object.

Deep copy (deepcopy): The deepcopy method of the copy module completely copies the parent object and its child objects.

>>>a = {1: [1,2,3]}
>>> b = a.copy()
>>> a, b({1: [1, 2, 3]}, {1: [1, 2, 3]})
>>> a[1].append(4)
>>> a, b({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
Copy after login

Deep copy requires the introduction of the copy module:

>>>import copy
>>> c = copy.deepcopy(a)
>>> a, c({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
>>> a[1].append(5)
>>> a, c({1: [1, 2, 3, 4, 5]}, {1: [1, 2, 3, 4]})
Copy after login

1. b = a.copy(): Shallow copy, a and b are an independent object, but their sub-objects still point to Unified object (is a reference).

The difference between deep and shallow copy in python

2. b = copy.deepcopy(a): Deep copy, a and b completely copy the parent object and its child objects, and they are completely independent.

The difference between deep and shallow copy in python

The above is the detailed content of The difference between deep and shallow copy in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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