Background:
Find out if Python's data types are mutable, or better understand Python's use of memory.
Variable and immutable definitions
Variable data type: Defines a variable in python that, when the value of the variable is modified, the memory address is not changed (the object is unchanged), the data is defined as a mutable data type.
Immutable data type: When a variable's value is modified, the memory address of the variable is changed (a new object is created) and is considered to be an immutable data type.
Test for the Python data type:
Digital:
111 ID (a) 1549733776 222 ID (a) 1549737328
Conclusion: The change of the memory address after the change of the variable value of the numeric type
String:
" ABCDEFG " ID (a) 2363386268560 " ABCDEFGGGGGG " ID (a) 2363386295024
Conclusion: The memory address changes after the variable value of the string type has changed
Meta-group:
>>> a = (' AA ', ' BB ', ' cc ') >>> ID (a) 2363384788456>>> a = (' AA ', ' BB ', ' DD ') >>> ID (a) 2363384789896
Conclusion: The change of the memory address after the variable value of the tuple type has changed
List:
>>> a = [' AA ', ' BB ', ' CC ']>>> ID (a) 2363386243016>>> a[0] = 11>>> a[11, ' BB ', ' CC ']> >> ID (a) 2363386243016
Conclusion: The memory address has not changed after the variable value of the list type has changed
Dictionary
>>> a = {' name ': ' Zhangsan ', ' age ': '}>>> ' ID (a) 2363384325384>>> a[' name '] = ' Lisi ' >> > a{' name ': ' Lisi ', ' age ': '}>>> ' ID (a) 2363384325384
Conclusion: The memory address has not changed after the variable value of the dictionary type has changed
Summary: When a variable value is a numeric, string, tuple data type, the value changes after the memory address changes, thinking that a new object was created. Therefore immutable data types are: numbers, strings, tuples.
When the variable value is a list, the dictionary data type, the value changes after the memory address has not changed, thinking that the change is still on the same object, so the mutable data type is: List, dictionary.
Variable and immutable data types for Python