Mutable objects, immutable objects

Source: Internet
Author: User

Immutable objects are strings, tuples, and so on

mutable objects are lists, dictionaries, collections, and so on.

A shallow copy simply adds a new object reference to the existing memory. ,

A deep copy is a re-application of a new memory so that this is a reference to the new memory address of the new object.

Frequently occurs for variable object references.

Consider the following two-segment code:

Code 1

L = [] forIinchRangeTen): L.append ({'Num': i}) Print (L) Result: [{'Num':0}, {'Num':1}, {'Num':2}, {'Num':3}, {'Num':4}, {'Num':5}, {'Num':6}, {'Num':7}, {'Num':8}, {'Num':9}]

Code 2

L =[]a= {'Num':0} forIinchRangeTen): a['Num'] =i l.append (a) print (l) print ('ID (l[0]):', ID (l[0]),'\nid (l[1]):', ID (l[1]) Result: [{'Num':9}, {'Num':9}, {'Num':9}, {'Num':9}, {'Num':9}, {'Num':9}, {'Num':9}, {'Num':9}, {'Num':9}, {'Num':9}]id (l[0]) :4542112ID (l[1]) :4542112

Conclusion:

The newly added object in L.append in code 1 is the newly created object,

The newly added object in L.append in code 2 is dictionary a, l[new] = A, l[new] is a new reference to the memory address of a, and all L[new] point to the same memory address. While dictionary A is a mutable object, the change of the data in the memory address after a changes. ,

Mutable objects, immutable objects

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.