Python replication and Reference Usage Analysis, python Reference Usage

Source: Internet
Author: User

Python replication and Reference Usage Analysis, python Reference Usage

This example describes how to copy and reference python. Share it with you for your reference. The specific analysis is as follows:

Simple replication is a reference

A = [, 4] B = a # This is reference B. append (2323) print (a, B) # ([1, 23, 4, 2323], [1, 23, 4, 2323])

Use copy. copy for shortest

Import copyc = copy. copy (B) # copy c. append (1) print (B, c) # ([1, 23,4, 2323], [1, 23, 4, 2323, 1]) list1 = [['a'], [1, 2, 4], [23, 'a'] list_copy = copy. copy (list1) # A new object is generated for the shortest copy, however, the attributes and content of the new object are still referenced by the original object. # When the new object is modified as a whole, the list_copy.append ('append') print (list_copy) # [['a'], [1, 2, 4], [23, 'a'], 'append'] print (list1) # [['a'], [1, 2, 4], [23, 'a'] # the original object is modified when the content of the new object is modified, because it still references list_copy [1]. append ('append + ') print (list_copy) # [['a'], [1, 2, 4, 'append +'], [23, 'a'], 'append'] print (list1) # [['a'], [1, 2, 4, 'append + '], [23, 'a']

Copy. deepcopy is used for iterative copying. After that, you can change the attributes of the new object without affecting the original object, but the efficiency and memory usage will decrease.

For list, dict, set, and so on, you can directly use x (object) and copy an object of the corresponding type. This is the simplest and most effective method.

I hope this article will help you with Python programming.

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.