Before we talk about what a dark copy is, let's look at a phenomenon like this:
A = [' Scolia ', 123, [],]b = a[:]b[2].append (666) print Aprint b
Why do I change only B, but it affects a? As I've seen in previous articles, the memory references are all saved in the sequence.
So, when we go through B to modify the empty list inside, it is actually to modify the same object in memory, so it will affect a.
A = [' Scolia ', 123, [],]b = A[:]print ID (a), ID (a[0]), ID (a[1]), ID (a[2]), print ID (b), id (b[0]), ID (b[1]), ID (b[2])
The code is verified correctly, so although A and B are two different objects, the references inside are the same. This is called the new object, the old content.
However, a shallow copy is not only so, see below:
A = [' Scolia ', 123, [],]b = a[:]b[1] = 666print Aprint b
What's going on here?
Seen me in the Python variable assignment description of the reunion know: for strings, numbers and other immutable data types, modification is equivalent to re-assignment. This is equivalent to refreshing the reference.
Code Validation:
A = [' Scolia ', 123, [],]b = a[:]b[1] = 666print ID (a), ID (a[0]), ID (a[1]), ID (a[2]) print ID (b), id (b[0]), ID (b[1]), ID (b[ 2])
Seems to be right.
These are shallow copies, summed up, shallow copy just copy a series of references, when we copied the object to the modifiable data type modification, and did not change the reference, so it will affect the original object. Modification of non-modifiable objects is a new object, the reference is refreshed, so the reference to the original object, the result is different.
To create a shallow copy method:
1. Slicing operations
2. Create a new object using the list () factory function. (b = List (a))
Then the deep copy is not the object referenced in the re-created again and generated a new series of references.
Basically, but for non-modifiable objects such as strings and numbers, recreating a copy seems a bit of a waste of memory, but you'll have to modify it to create a new object and refresh the reference anyway. So also use the original reference also does not matter, but also can achieve the purpose of saving memory.
Look at the code validation:
From copy import deepcopya = [' Scolia ', 123, [],]b = Deepcopy (a) b[1] = 666print ID (a), ID (a[0]), ID (a[1]), ID (a[2]) print ID (b), id (b[0]), ID (b[1]), ID (b[2])
Verify that it is correct.
Creation of deep copies:
1. As with the code example, it can only be created with the Deepcopy () method of the built-in copy module.
OK, the question about the depth of the copy is first here, there is something wrong or need to add to the future will continue.
This in-depth understanding of Python in the shallow copy and deep copy is a small part of the whole content to share to everyone, I hope to give you a reference, but also hope that we support topic.alibabacloud.com.