Introduction to reference and copy in Python

Source: Internet
Author: User
This article mainly introduces the reference and copy analysis in Python. It also describes deep copy and shallow copy, reference counting, and garbage collection, if an object's value can be modified, the object is said to be mutable. if the value cannot be modified, the object is said to be immutable.

Mutable variable types, such as list, set, and custom types (equivalent to the reference type in C );

Immutable unchangeable types, such as string and numbers (equivalent to the value type in C );

1. references and copies)

When the = value assignment operator is used in the program, such as a = B,

For immutable objects, a is created as a copy of B. a and B point to different memory addresses, and a and B are independent of each other.

The code is as follows:


Def TestCopy ():
A = 10
B =
A = 20
Print (B) # B still is 10


However, for mutable objects, a is created as a reference of B. elements a and B share the same memory address. elements a and B share the same memory address.

The code is as follows:


Def TestRef ():
A = [1, 2, 4]
B = a # B is a reference to
Print (B is a) # True
B [2] =-100 # change an element in B
Print (a) # a also changed to [,-]

II. shallow copy and deep copy)

To avoid a mutable object pointing to the same object, you must create a new copy instead of a reference.
In python, you can use two copies for container objects (such as lists and dictionaries): shortest copy and deep copy.

Create a new object in the shortest copy, but use the reference of the elements of the original object (if it is of the same type, it is equivalent to the copy) to fill in the new object. You can use copy. copy () to perform the shortest.

The code is as follows:


Def TestShallowCopy ():
A = [1, 2, [3, 4]
B = list (a) # create a shallow copy of
Print (B is a) # False
B. append (100) # append element to B
Print (B)
Print (a) # a is unchanged
B [2] [0] =-100 # modify an element inside B
Print (B)
Print (a) # a is changed

In this example, a and B share the same variable element. Therefore, you can modify the elements in one list object and the other list object.

Create a new object and recursively copy all the elements contained in the object. You can use copy. deepcopy () to perform deep copy.

The code is as follows:


Def TestDeepCopy ():
Import copy
A = [1, 2, [3, 4]
B = copy. deepcopy ()
B [2] [0] =-100
Print (B) # B is changed
Print (a) # a is unchanged

In this example, a and B are opposite list objects, and their elements are independent of each other.

III. reference count and garbage collection

All objects in python are referenced and counted. When an object is assigned or added to a container, its reference count is automatically increased. when del is used or the variable value is assigned to another value, the reference count is automatically reduced. when the reference count is 0, the python garbage collector recycles this variable.

The code is as follows:


Def TestGarbageCollection ():
Import sys
Print (sys. getrefcount (37 ))
A = 37 # Creates an object with value 37
Print (sys. getrefcount (37 ))
B = a # Increases reference count on 37
Print (sys. getrefcount (37 ))
C = []
C. append (B) # Increases reference count on 37
Print (sys. getrefcount (37 ))
Del a # Decrease reference count of 37
Print (sys. getrefcount (37 ))
B = 42 # Decrease reference count of 37
Print (sys. getrefcount (37 ))
C [0] = 2.0 # Decrease reference count of 37
Print (sys. getrefcount (37 ))

TestGarbageCollection ()

The running result is:

The code is as follows:


11
12
13
14
13
12
11


Why are 11 references in the first place? Who knows?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.