Python shared reference (multiple variable references) sample code _python

Source: Internet
Author: User

Copy Code code as follows:

A = 3
b = A

The first picture (Figure 1), you can see it at a glance:


Variable names and objects, after running assignment statement B = A, the variable a,b points to the memory space of object 3.
Assuming that you execute a = ' python ', a will point to the string object you just created.
Let's try this again:

Copy Code code as follows:

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

Result

Copy Code code as follows:

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


From my understanding to explain the words: List is a type object, and each element in the object can be regarded as a variable, to reference the different memory space object list_1 = [1,2,3,4] is to let List_1 point to the list of memory space, list_2 = list_1, They will point to the same memory space. When list_1[0] changes direction, the list_2 still points to the list object, so it looks like the value of changing list_1[0], in fact Python is modified by list_1 directly to the memory space, and the list_2 points to no variables.
Perhaps the result is not what we want. If you don't want this to happen, you need to copy the Python object instead of creating the reference.
Such as:


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.