Python shared reference (multiple variable references) Sample code

Source: Internet
Author: User
How is a single (one) python object referenced by multiple variables? The code below is as follows:


A = 3
B =

First (), you can see at a glance:


Variable name and object. after running the value assignment statement B = a, both variables a and B point to the memory space of object 3.
If a = 'Python' is executed, a points to the created String object.
Let's try again:

The code is as follows:


>>> List_1 = [1, 2, 4]
>>> List_2 = list_1
>>> List_2
>>> List_1 [0] = 'Python'
>>> List_2

Result:

The code is as follows:


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



In my understanding, list is a type object, and every element in the object can be regarded as a variable, referencing the object list_1 = [1, 2, 3, 4] is to point list_1 to the memory space of the list. when list_2 = list_1, they will point to the same memory space. When the value of List_1 [0] is changed, list_2 still points to the list object, so the value of list_1 [0] is changed, in fact, python directly makes changes to the memory space through list_1, and there is no variable pointing to list_2.
Maybe this result is not what we want. If you do not want this to happen, you need to copy python objects instead of creating references.
For example:

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.