Python base: Python mutable objects and immutable objects

Source: Internet
Author: User

Python allocates objects in the heap into two categories: mutable objects and immutable objects. The so-called mutable object means that the object's contents are mutable, such as list. Immutable objects, in contrast, indicate that their contents are immutable.

Immutable object: Int,string,float,tuple

Variable object: list,dictionary

For global variables, mutable objects differ greatly from immutable objects.

I. Immutable objects

Because variables in Python hold object references, object references to variables are mutable for non-mutable objects, although the object itself is immutable. The use of such mechanisms can sometimes confuse people, and it seems that mutable objects change. As in the following code:

i =

i + = 2

From the above, the immutable object has not changed, it is still an immutable object, the change is just the creation of a new object, changing the object reference of the variable.

Take a look at the code below to show this.

Second, for variable objects

The content of its objects can vary. When the content of an object changes, the object reference of the variable does not change. As the following example.

m=[5,9]

m+=[6]

Python base: Python mutable objects and 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.