Python light copy and deep copy - Python zero basics tutorial

catalogue

Zero basic Python learning route recommendation: Python learning directory >> Getting started with Python Basics

I Python shallow copy and deep copy Preface

What is shallow copy / deep copy? To put it bluntly, it is actually data copy. What is the difference between the two? It sounds confused, Python You may encounter such a pit when developing a project;

II Python ordinary variable assignment

The variable assignment we usually use is shallow copy, that is, two variables share the same memory block and the same memory address. Once the value changes, the value of another variable will change with it. The demonstration code is as follows:

# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:Ape programming
@Blog(Personal blog address): www.codersrc.com
@File:Python Light copy and deep copy.py
@Time:2021/3/29 07:37
@Motto:No small steps lead to thousands of miles. No small streams lead to rivers and seas. The brilliance of program life needs to be accumulated unremittingly!

"""

list1 = [1,2,3,4,5]
# Universal variable assignment
list2 = list1
print(id(list1))
print(id(list2))

# Modify the data of list list2
list2.append(123)
print(list1)
print(list2)

'''
Output results:
2251297055368
2251297055368
[1, 2, 3, 4, 5, 123]
[1, 2, 3, 4, 5, 123]

'''

Note: the conventional variable assignment shares a memory block with the same memory address. Once the value changes, the values of all variables sharing the same memory address will change, which can be used directly Built in function id Compare the memory address!

III Python shallow and deep copies

In the process of Python development, sometimes the above situation is not what we want. We prefer to modify the assigned variable without affecting the value of the original variable. How to implement it? Here we need to introduce copy module:

copy.copy – shallow copy, reallocate memory, copy only the parent object, not the internal child object of the object;

copy.deepcopy – deep copy, reallocate memory, copy objects and all their sub objects;

1.Python shallow copy

# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:Ape programming
@Blog(Personal blog address): www.codersrc.com
@File:Python Light copy and deep copy.py
@Time:2021/3/29 07:37
@Motto:No small steps lead to thousands of miles. No small streams lead to rivers and seas. The brilliance of program life needs to be accumulated unremittingly!

"""

import copy
spam = ['A', 'B', 'C', 'D']
# Use light copy
cheese = copy.copy(spam)
cheese[1] = 42
print(id(spam),spam)
print(id(cheese),cheese)

'''
Output result:
57205555 ['A', 'B', 'C', 'D']
57208888 ['A', 42, 'C', 'D']
'''

2.Python deep copy

# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:Ape programming
@Blog(Personal blog address): www.codersrc.com
@File:Python Light copy and deep copy.py
@Time:2021/3/29 07:37
@Motto:No small steps lead to thousands of miles. No small streams lead to rivers and seas. The brilliance of program life needs to be accumulated unremittingly!

"""


import copy
spam = ['A', 'B', 'C', 'D']
# Use deep copy
cheese = copy.deepcopy(spam)
cheese[1] = 42
print(id(spam),spam)
print(id(cheese),cheese)

'''
Output results:
57205555 ['A', 'B', 'C', 'D']
57208888 ['A', 42, 'C', 'D']

'''

3. Difference between shallow copy and deep copy

**For conventional Dictionary dict perhaps List list There is no difference between using a deep copy or a shallow copy of the copy module** If there are subclasses in the dictionary or list, the results will be very different if you use the deep copy and shallow copy of the copy module:

copy.copy - reallocate memory, copy only the parent object, not the child object inside the object;

copy.deepcopy - reallocate memory and copy the object and all its sub objects;

The example code is as follows:

# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:Ape programming
@Blog(Personal blog address): www.codersrc.com
@File:Python Light copy and deep copy.py
@Time:2021/3/29 07:37
@Motto:No small steps lead to thousands of miles. No small streams lead to rivers and seas. The brilliance of program life needs to be accumulated unremittingly!

"""

import copy

print("Use shallow copy:")
spam = [['A','E'], 'B', 'C', 'D']
# Use light copy
cheese = copy.copy(spam)
cheese[0][0] = 42
print(id(spam),spam)
print(id(cheese),cheese)
print("***"*20)

print("Use deep copy:")
spam = [['A','E'], 'B', 'C', 'D']
# Use deep copy
cheese = copy.deepcopy(spam)
cheese[0][0] = 42
print(id(spam),spam)
print(id(cheese),cheese)

'''
Output result:
Use shallow copy:
2179653046408 [[42, 'E'], 'B', 'C', 'D']
2179653046920 [[42, 'E'], 'B', 'C', 'D']
************************************************************
Use deep copy:
2179653086728 [['A', 'E'], 'B', 'C', 'D']
2179653046408 [[42, 'E'], 'B', 'C', 'D']

'''

thus it can be seen:

**If the list or dictionary does not contain sub lists or sub dictionaries, the effect of using deep copy or shallow copy is the same**

**If there are subclasses in the list or dictionary, only the deep copy will reallocate memory for all subclasses, while the shallow copy is only responsible for the parent object, regardless of the child object**

IV Guess you like it

  1. Python configuration environment
  2. Python variables
  3. Python operator
  4. Python conditional judgment if/else
  5. Python while loop
  6. Python break
  7. Python continue
  8. Python for loop
  9. Python string
  10. Python list
  11. Python tuple
  12. Python dictionary dict
  13. Python conditional derivation
  14. Python list derivation
  15. Python dictionary derivation

No reprint without permission: Ape programming ยป Python shallow and deep copies

Added by ramez_sever on Thu, 03 Feb 2022 09:38:59 +0200