Copying objects in python

Source: Internet
Author: User

Copying objects in python

In python, both parameter passing and function return values are referenced and passed. So how to copy objects? The copy module of the Standard Library provides two methods: copy and deepcopy.

1. copy. copy: only the parent object is copied, and the internal sub-objects of the object are not copied.
2. copy. deepcopy: Deep copy object and its sub-objects

See the following example:

Import copya = [1, 2, 3, 4, ['A', 'B'] # original object e = a [:] # using the multipart operation for copying (shallow copy) B = a # assign a value and pass the reference c = copy of the object. copy (a) # object copy, shortest copy d = copy. deepcopy (a) # object copy, deep copy. append (5) # modify the object aa [4]. append ('C') # modify ['A', 'B'] list sub-object print 'a = ', aprint' B = ', bprint 'C =' in object ', cprint 'd = ', d
Running result:

A = [1, 2, 3, 4, ['A', 'B', 'C'], 5]
B = [1, 2, 3, 4, ['A', 'B', 'C'], 5]
C = [1, 2, 3, 4, ['A', 'B', 'C']
D = [1, 2, 3, 4, ['A', 'B']
E = [1, 2, 3, 4, ['A', 'B', 'C']
Analysis:

B is a reference of a. The two point to the same object, and the printed results must be the same. C Only copies the parent object of a, but does not copy the list of child objects nested in a. Therefore, 1, 2, 3, and 4 in c are copies of their own, however, the nested sub-Object List is still a's original. D. Because it is a deep copy, the parent object of the sub-object is a new copy generated by copying, which is completely unaffected by. As for e, the effect of the multipart operation is equivalent to that of the shortest copy, and the result is the same as that of c.


In addition, the dictionary also has its own copy method, but there is no deepcopy method. Its copy method is the same as the copy method in the copy module above, and it is also the implementation of the shortest copy method.


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.