Python Reference copy Assignment

Source: Internet
Author: User
Tags garbage collection shallow copy

Amway is a Web site that is useful for learning programming:
http://www.pythontutor.com/

You can visually execute the code on a row-by-line basis and experience it yourself

This site is also I look at other people's blog when found, but also first put on the understanding of others, I think the writing is very good:

REF:

Python object reference, variability, and garbage collection

Python in-depth understanding of assignments, references, copies, scopes

As the saying goes, the master leads the door, and the practice depends on the individual. It wasn't long before I learned Python, and in 17, I went through the grammar, and it should not be over. Byte-of-python at that time.

I think this book is OK, light weight, if you learn a programming language should be very fast. Recently began to watch the video study, looked for a few days, but did not actually write what program come out.

To the back of the video feel can't keep up, immediately understand that they should stop. Those knowledge needs to be slowly digested, not to do it!

It's always a blur when using Python, this time to solve the problem of reference assignment.

The above two articles are very clear, I will quietly cut them, easy to understand:

Mutable objects and immutable objects

In Python, objects are divided into two types: mutable objects and immutable objects, immutable objects including Int,float,long,str,tuple, and mutable objects including list,set,dict. It is important to note that immutable refers to the immutable value of the variable. For variables of an immutable type, if you want to change the variable, a new value is created that binds the variable to the new value, and the old value waits for garbage collection if it is not referenced. In addition, the immutable type can calculate the hash value as the dictionary key. When mutable type data is applied to an object, it is not necessary to apply the memory elsewhere, just to request (+/-) continuously after this object, that is, its memory address will remain unchanged, but the area will grow or become shorter.

Example:

1 #Immutable2A = 123 Print(ID (a))4A=15 Print(ID (a))6St ="thisisastring"7 Print(ID (ST))8St ="string"9 Print(ID (ST))Ten  One #mutable ALi = [12,12,342,4] - Print(ID (LI)) -Li.append (12) the Print(ID (LI)) -  - #a new list -Li = [12,123,213,123,123] + Print(ID (LI))
1094336010943008140417189762736140417373204184140417198413960140417198413960140417198537224

As can be seen, when the object is immutable, re-assignment, the address has changed, that is, rebind "paste" to the new value up.

When the object is variable, such as the list in the previous example, after appending (append) an element, the address does not change, just add an element on the original base.

The following sentence

Li = [12,123,213,123,123]

Instead of recreating a list and pointing Li to it, the address obviously changed.

Assignments and references

The variable names in Python should be interpreted as tags, which are often referred to as references. The reference value of the object is always passed to the variable when the value is assigned.

a=12B=aprint(ID (a), id (b)) b=13print(ID (a), id (b))
10943360 1094336010943360 10943392

When an object is immutable, assigning a value to an existing variable creates a new object and then passes the new reference value to the variable. The previously contacted program language always has the same address and changes its value.

At first B=a,b obtained a reference, so the address of AB is the same, while assigning a new value to B, re-created the object, and then paste the B up, so the address of the AB is different.

 1  mylist= [12,13,1234 2  anotherlist = mylist  3  Anotherlist.append (999)  4  print   (Mylist,id (mylist), ID (anotherlist))  5   Mylist[0]  6  print   (anotherlist,mylist)  7  8  del   Anotherlist  9  print  (Mylist,id (mylist)) 
1 [1234, 999] 140417198414536 1404171984145362 [1234, 999] [1234, 999]3 [13, 1234, 999] 140417198414536

When the object is variable, a list is assigned to another list, and the new list is actually quoted.

So mylist and Anotherlist actually point to an object,

Then append an element to anotherlist, then delete the first element, because it points to an object, so the output is the same.

The last deletion of anotherlist just removes the tag, because the object they point to is also mylist used. (Well, this site really helps to understand)

Copy

So how exactly would an object be created as a separate pair (Bian) image (Liang) like the one previously learned, as in the C language?

In Python this operation is called a copy, the copy is divided into two kinds, shallow copy (copy), deep Copy (deepcopy).

It says, the direct assignment is worth the reference, to want to copy will have to use other operations, a common list of slices, list () method, copy () method.

Alist = [12,12,12,23,23213]
Blist = alist[:]
CList = List (alist)
From copy import copy
dlist = Copy (alist)
Print (alist==blist==clist)
Print (ID (alist), id (blist), ID (clist))
Alist.append (77)
Print (alist==blist==clist)
Print (ID (alist), id (blist), ID (clist))

True140417198414216 140417198609096 140417189752712false140417198414216 140417198609096 140417189752712

The object is equal but the address is different, it is true that a new object is created, and then an element is appended to Alist, and the three are not equal.

= = and is

Here's the difference between the two,

x = [1, 2, 3= [1, 2, 3]print(x = = y)print is y)print
    (ID (x))print(id (y)) execution result: TrueFalse21941448179282194144817288

= = Compares objects for equality, is compares references for equality, x and Y objects are all-in-one but they are actually different objects, just the values are the same, and then x and Y are different references to different objects that are equal.

Why is that a shallow copy?

1 alist = [12,12,12,[12,23],23213]2 blist = alist[:]3 blist.append (777 )4 blist[3][0]=215 alist[3][1]=326print(alist,blist)
[12, 12, 12, [21, 32], 23213] [12, 12, 12, [21, 32], 23213, 777]

From the output of the results see, whether from alist to change alist[3] or blist to change blist[3], the result alist and blist of the 3rd elements have changed, such a copy is called a shallow copy, it only copied the outermost layer.

Of course the picture is easier to understand:

From the picture you can see that the other elements are re-copied and created, but the number 3rd element is still a reference, the same as the one in the original alist. So any list to modify element number 3rd the other side will follow the change.

Append and Extend

Let's break the difference between the two:

1 alist = [12,12,12,[12,23],23213]2 blist = list (alist)3 alist.append ([ 12,777])4 blist.extend ([12,777])5print(alist)6  Print(blist)
[[12], [], 23213, [12],]][, 12, [12, 23], 23213, 12, 777]

Look at the output and you know it's different.

Further exploration of deep copy:

1Alist = [12,12,[12,23],23213]2Blist =alist[:]3  fromCopyImportdeepcopy4CList =deepcopy (alist)5 Print(alist==blist==clist)6 Print(ID (alist), id (blist), ID (clist))7 Print(ID (alist[2]), ID (blist[2]), ID (clist[2]))8alist[2][0]=7779 Print(Alist), (blist), (CList))
True140417189861576 140417189752008 140417189860744140417198413960 140417198413960 140417198612360[12, 12, [777, 23], 23213] [12, 12, [777, 23], 23213] [12, 12, [12, 23], 23213]

Blist by a shallow copy of the list () method, clist by the alist deep copy, the third line of the output address is visible for the 2nd element (a sub list) address, alist,blist the same, and clist and they are different, is re-created.

The result of the final printing also shows that the shallow copy is just a copy of the outer layer, for the number 2nd element is still the same reference.

To be Continued ...

Python Reference copy Assignment

Related Article

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.