"Go" Python Shared reference (multiple variable references) sample code

Source: Internet
Author: User

Python shared reference (multiple variable references) sample Code _python_ script House
Http://www.jb51.net/article/44109.htm

How is it that Python single (one) object is referenced by multiple variables? Look at the code below


A = 3
b = A

First (Figure 1), you can see at a glance:

Variable name and object, after running assignment statement B = A, the variable A, a, is pointing to the memory space of object 3. Assuming that a = ' python ' is executed at this point, a points to the string object you just created. Let's try this situation again:


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

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

In my understanding, the list is a type object, and each element in the object can be regarded as a variable, referring to an object of different memory space list_1 = [1,2,3,4] is the memory space where list_1 points to the list, list_2 = List_1, They will point to the same memory space. When list_1[0] changes point, list_2 still points to the list object, so to see is to change the value of list_1[0], in fact, Python through the list_1 directly to the memory space to do the modification, list_2 point to no variables. Maybe the result isn't what we want. If you do not want this to happen, you need a Python object copy instead of creating a reference. Such as:

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.