Python replication and reference

Source: Internet
Author: User

Python replication and reference

Simple replication is a reference

a=[1,23,4]b=a # This is a referenceb.append(2323)print(a,b) #([1, 23, 4, 2323], [1, 23, 4, 2323])

 

Use copy. copy for shortest

import copyc=copy.copy(b)# Copyc.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, but the attributes and content of the new object are still references to the original object.# When the new object is modified as a wholelist_copy.append('append')print(list_copy)#[['a'], [1, 2, 4], [23, 'a'], 'append']print(list1)#[['a'], [1, 2, 4], [23, 'a']] # When modifying the content of the new object, the original object is modified because it is still referenced.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.

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.