Python reference and copy

Source: Internet
Author: User

Python reference:
In python, when an internal value variable is assigned, a reference variable is passed, which is similar to that of the C language,
For example
A = [1, 2, 3]
The address where variable A saves the list
In python, you can use ID () to query
The address of a in the memory is: 675375852
B =
What is B's content, and what is the address?
Output the content of B in print is also [1, 2, 3].
Then let's check the address of B to see if it can verify our conclusion.
Print ID (B)
Sure enough, the address of B is also: 675375852
The conclusion is correct.

This will cause a problem because both variable A and variable B store the address of the same list. If I change the value of the list to which a points,
The value of the List pointed to by B also changes.
For example:
A [1] = 6
Print
The output content is [1, 6, 3].
Print B
The content of the list pointed to by B is also [, 3]


Python copy

If we only want to modify the content in list. Instead of modifying B's content, you need to use Python copy.
A = [1, 2, 3]
B = A [:] ### copy the content of A to B
A [1] = 6
Print
The output content of A is [1, 6, 3].
The content of B is not [1, 6, 3]
Instead, it is [1, 2, 3].

Haha, python is amazing !!


OriginalArticle: Http://www.cnpythoner.com/post/20.html. Please reserve the file. Thank you!

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.