Immutable and mutable objects in Python

In Python, objects can be divided into two categories: Mutable Objects and Immutable Objects .

Immutable Objects :

  1. Number (int) : Integers are immutable, i.e. x = 5you cannot change xthe value of , but you can reassign it to x.

  2. Float : Floating point numbers are also immutable.

  3. String (str) : String is immutable. You cannot change the original string, but you can create a new string.

  4. Tuple : Tuples are also immutable. Once created, the elements within them cannot be changed.

  5. Frozenset : Unlike sets, frozen sets are immutable, and once created, the elements within them cannot be changed.

Mutable Objects :

  1. List : Lists are mutable, you can change, add or remove elements from the list.

  2. Set : Sets are mutable, you can add or remove elements from the set.

  3. Dictionary (dict) : Dictionaries are mutable, you can add, delete or modify key-value pairs in the dictionary.

  4. Custom objects (classes) : If you create a class and define methods that can change the properties of the object, then instances of that class are also considered mutable.

Mutable objects can be changed during their lifetime, whereas immutable objects cannot change their contents once they are created.

This distinction is important for understanding Python's behavior and rules, especially when dealing with function parameters, return values, etc. For example, when you pass mutable objects to a function, the function may change those objects. For immutable objects, the function cannot change the original object and can only return a new object.

Guess you like

Origin blog.csdn.net/weixin_44943389/article/details/133011657