Shallow and deep copies in Python

Source: Internet
Author: User

1. Lists and dictionaries, directly assigned, are shallow copies, where both sides point to the same address, because Python passes by reference to mutable objects.

>>> a = [1, 2, 3]>>> B =a>>>b[1, 2, 3]>>> A[0] ='Apple'>>>a['Apple', 2, 3]>>>b['Apple', 2, 3]>>> >>> >>> dic = {'a':'Apple','b':'Banbana'}>>> Dic2 =DiC>>>dic2{'a':'Apple','b':'Banbana'}>>> dic['b'] ='Blueberry'>>>dic{'a':'Apple','b':'Blueberry'}>>>dic2{'a':'Apple','b':'Blueberry'}

2. For a non-nested list, use a full slice [:], the factory function list (), or copy.copy () are deep copies.

 >>> A = [1, 2, 3 >>> b = >>> c = a[:]  >>> import   copy  >>> d = Copy.copy (a)  > >> >>> a[0] =    '  >>>

3. For non-nested dictionaries, use the Factory function Dict (), or copy.copy () are deep copies.

>>> dic = {'a':'Apple','b':'Banana'}>>> Dic2 =dict (DIC)>>>ImportCopy>>> DIC3 =copy.copy (DIC)>>> >>> dic['b'] ='Blueberry'>>>dic{'a':'Apple','b':'Blueberry'}>>>dic2{'a':'Apple','b':'Banana'}>>>dic3{'a':'Apple','b':'Banana'}

4. For nested lists, nested dictionaries can only use copy.deepcopy () to implement deep copies.

>>>ImportCopy>>> >>> A = [1, 2, ['Apple']]>>> B =Copy.deepcopy (a)>>> A[2][0] ='Watermelon'>>>a[1, 2, ['Watermelon']]>>>b[1, 2, ['Apple']]>>> >>> >>> dic = {'a':'Apple','b': {'B1':'Banana','B2':'Blueberry'}}>>> Dic2 =copy.deepcopy (DIC)>>> dic['b']['B1'] ='Bukeneng'>>>dic{'a':'Apple','b': {'B1':'Bukeneng','B2':'Blueberry'}}>>>dic2{'a':'Apple','b': {'B1':'Banana','B2':'Blueberry'}}

5. For tuples that Nest mutable objects, only copy.deepcopy () implements a deep copy.

>>>ImportCopy
>>>>>> T = (1, 2, ['Apple'])>>> t2 =T>>> t3 =tuple (t)>>> T4 =copy.copy (t)>>> T5 =copy.deepcopy (t)>>> >>> T[2][0] ='Watermelon'>>>T (1, 2, ['Watermelon'])>>>T2 (1, 2, ['Watermelon'])>>>T3 (1, 2, ['Watermelon'])>>>T4 (1, 2, ['Watermelon'])>>>T5 (1, 2, ['Apple'])

Finish.

Shallow and deep copies in Python

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.