Python shares references to multiple variables to reference sample code

  • 2020-04-02 13:14:36
  • OfStack


a = 3
b = a

Let's start with the figure above (figure 1). It's easy to see:

< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201312/20131204112421.jpg? 2013114112911 ">


The variable name and the object, after the assignment statement b = a is run, the variables a and b both point to the memory space of object 3.
Assuming that a = 'python' is executed, a will point to the string object just created.
Let's try this again:


>>>list_1 = [1,2,3,4]
>>>list_2 = list_1
>>>list_2
>>>list_1[0] = 'python'
>>>list_2

The result:


[1,2,3,4]
['python',2,3,4]


< img SRC = "border = 0 / / files.jb51.net/file_images/article/201312/20131204112522.jpg? 2013114113031 ">

From my understanding, it is explained that list is a type object, and each element in the object can be regarded as a variable. To reference the object list_1 = [1,2,3,4] with different memory space is to make list_1 point to the memory space of the list. When list_2 = list_1, they will point to the same memory space. When List_1[0] changes the direction, list_2 still points to the list object, so it is seen that the value of List_1[0] is changed. In fact, python directly goes to the memory space to modify the direction of list_2 without any variable.
Maybe that's not what we want. If you don't want this to happen, you need to copy python objects instead of creating references.
Such as:

< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201312/20131204112556.jpg? 2013114112646 ">


Related articles: