Home >Backend Development >Python Tutorial >Copy operations in Python and shallow copy and deep copy methods in the copy module

Copy operations in Python and shallow copy and deep copy methods in the copy module

WBOY
WBOYOriginal
2016-07-22 08:56:371469browse

It is often necessary to copy an object in a program. The idea should be as follows

a = [1, 2, 3]
b = a

# [1, 2, 3]
print b 

It has been copied, but now you need to change the value of the first element to 5

b[0] = 5 

# [5, 2, 3]
print b 

# [5, 2, 3]
print a 

I changed the value of the first element of b, but the value of a also changed. This is because = in python is a reference. a and b point to the same list, so changing the list will cause the above Result.

The solution is slicing

a = [1, 2, 3]
b = a[:]
b[0] = 4

# [1, 2, 3]
# [4, 2, 3]
print a
print b

But when it comes to nested lists, give it a try

a = [[1,2,3], 4, 5]
b = a[:]
b[1] = 0 

# [[1,2,3], 4, 5]
# [[1,2,3], 0, 5]
print a
print b

Yeah! No problem, let’s try nested list elements

a = [[1,2,3], 4, 5]
b = a[:]
b[0][0] = 5

# [[5,2,3], 4, 5]
# [[5,2,3], 4, 5]
print a
print b
b = a[:]

The value of a still changes. Slice copy only copies the object and does not copy the sub-elements

copy module

The copy module is used to copy objects. This module is very simple and only provides two main methods: copy.copy and copy.deepcopy, which represent shallow copy and deep copy respectively. What is shallow copying and what is deep copying? There are truckloads of information on the Internet, so I won’t go into detail here. The copy operation only works on composite objects. Use simple examples to introduce these two methods respectively.

Shallow copy only copies the object itself and does not copy the objects referenced by the object.

#coding=gbk
import copy
l1 = [1, 2, [3, 4]]
l2 = copy.copy(l1)
print l1
print l2
l2[2][0] = 50
print l1
print l2

Result:

[1, 2, [3, 4]]
[1, 2, [3, 4]]
[1, 2, [50, 4]]
[1, 2, [50, 4]]

The same code, using deep copy, the results are different:

import copy
l1 = [1, 2, [3, 4]]
l2 = copy.deepcopy(l1)
print l1
print l2
l2[2][0] = 50
print l1
print l2

Result:

[1, 2, [3, 4]]
[1, 2, [3, 4]]
[1, 2, [3, 4]]
[1, 2, [50, 4]]

Change the default behavior of copy

When defining a class, you can change the default behavior of copy by defining the __copy__ and __deepcopy__ methods. Here is a simple example:

class CopyObj(object):
  def __repr__(self):
    return "CopyObj"
  
  def __copy__(self):
    return "Hello"
obj = CopyObj()
obj1 = copy.copy(obj)
print obj
print obj1

Result:

CopyObj
Hello
Statement:
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