The depth copy in Python

Source: Internet
Author: User
Tags shallow copy

Two, depth copy

1, first look at the assignment operation.

L1 = [1,2,3,[' Barry ', ' alex ']]l2 = l1l1[0] = 111print (L1)  # [111, 2, 3, [' Barry ', ' Alex ']]print (L2)  # [111, 2, 3, [ ' Barry ', ' Alex ']]l1[3][0] = ' wusir ' Print (L1)  # [111, 2, 3, [' Wusir ', ' Alex ']]print (L2)  # [111, 2, 3, [' Wusir ', ' al ' Ex ']]

For an assignment operation, L1 and L2 point to the same memory address, so they are exactly the same.

2, shallow copy copy.

L1 = [1,2,3,[' Barry ', ' Alex ']
L2 = L1.copy () print (L1,id (L1)) # [1, 2, 3, [' Barry ', ' Alex ']] 2380296895816print (L2,id (L2)) # [1, 2, 3, [' Barry ', ' Alex '] 2380296895048
L1[1] = 222
Print (L1,id (L1)) # [1, 222, 3, [' Barry ', ' Alex ']] 2593038941128
Print (L2,id (L2)) # [1, 2, 3, [' Barry ', ' Alex ']] 2593038941896

L1[3][0] = ' wusir ' Print (L1,id (l1[3])) # [1, 2, 3, [' Wusir ', ' Alex ']] 1732315659016print (L2,id (l2[3])) # [1, 2, 3, [' Wusir ', ' Alex '] 1732315659016

For shallow copy, the first layer creates a new memory address, and from the second level it points to the same memory address, so consistency is maintained for the second layer and the deeper layers.

3, deep copy deepcopy.

Import COPYL1 = [1,2,3,[' Barry ', ' alex ']]l2 = copy.deepcopy (L1) print (L1,id (L1))  # [1, 2, 3, [' Barry ', ' Alex ']] 2915377 167816print (L2,id (L2))  # [1, 2, 3, [' Barry ', ' Alex ']] 2915377167048l1[1] = 222print (L1,id (L1))  # [1, 222, 3, [' Bar Ry ', ' Alex ']] 2915377167816print (L2,id (L2))  # [1, 2, 3, [' Barry ', ' Alex ']] 2915377167048l1[3][0] = ' wusir ' Print (L1, ID (l1[3])  # [1, 222, 3, [' Wusir ', ' Alex ']] 2915377167240print (L2,id (l2[3]))  # [1, 2, 3, [' Barry ', ' Alex ']] 291537 7167304

For deep copy, the two are completely independent, changing any element of any one (no matter how many layers), and the other absolutely does not change.

The depth copy in Python

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.