Spatial Address Changes in Python Object Assignment Operations

In Python, object assignment is a simple object reference, which is similar to C++ Different. As follows:

List_A= [1,2,3, hello, Python, C].

List_B= List_A.

In this case, the list_B and list_A is the same, they point to the same memory, list_B is just a list_The alias of a is a reference.

We can use a list_B is a list_To determine, return true, indicating that they have the same address and content. You can also use id (x) for x in list_a. List_B to view the addresses of two lists.

The assignment operation (including using objects as parameters and returning values) does not open up new memory space, it only copies the reference of the new object . That is to say, besides the list_There is no other memory overhead besides the name b.

Modified the list_a. It affects the list_B; Similarly, the list has been modified_B has affected the list_A.

Simple object assignment and slice assignment

Let's take a look at a piece of code first:

c = [1,3,2]
print('initial c value :',c)
d = c                                   #simple object assignment 
print('c related to d are the addresses the same :',d is c)      #determine whether the object addresses after simple object assignment are the same 
e = c[::]                               #slice assignment 
print('initial d value :',d)                     
c.sort()                                #right c sort 
print('c reassigned cd value :')
print('c value is :',c)
print('d value is :',d)
print('slice assignment e value :',e)

Output as:

 the following is the assignment of values to list objects 
 initial c value : [1, 3, 2]
c related to d are the addresses the same : True
 initial d value : [1, 3, 2]
c reassigned cd value :
c value is : [1, 2, 3]
d value is : [1, 2, 3]
 slice assignment e value : [1, 3, 2]

We found that using c.sort() only sorts the data in the original created space (where cd points to that area). The output cd value is the same (all sorted values in the original space).

But if we take the c. Sort() Change to C= What about [3,5,4]? Will the output of d still be the same as c at this time .

Let's take a look at the output results:

 the following is the assignment of values to list objects 
 initial c value : [1, 3, 2]
c related to d are the addresses the same : True
 initial d value : [1, 3, 2]
c reassigned cd value :
c value is : [3, 5, 4]
d value is : [1, 3, 2]
 slice assignment e value : [1, 3, 2]

We found that the value of cd after reassigning c is:
The c value is: [3, 5, 4]
The d value is: [1, 3, 2].

The two are different!

Why is this? The reason is: C= [] indicates the reopening of an empty area, while. sort() is just an operation on the original area (no new area has been opened) .

The diagram is as follows: .