What are the immutable data types in python?
There are three immutable data types in Python, namely integers, strings and tuples.
Integer type
a = 1 print(id(a),type(a)) a = 2 print(id(a),type(a)) 19124992321912499264
We can find that when the data changes, the memory address of the variable changes, then the integer type is an immutable data type.
String
b = 'djx' print(id(b),type(b)) b = 'djx1996' print(id(b),type(b)) 535056476344535056476624
We can find that when the data changes, the memory address of the variable changes, then the string is an immutable data type.
Tuple
Tuple is called a read-only list, that is, the data can be queried, but cannot be modified, but we can store it in the elements of the tuple A list that checks whether a tuple is mutable or immutable by changing the value of the list.
c1 = ['1','2'] c = (1,2,c1) print(c,id(c),type(c)) c1[1] = 'djx' print(c,id(c),type(c)) result: (1, 2, ['1', '2']) 386030735432(1, 2, ['1', 'djx']) 386030735432
We can find that although the tuple data has changed, the memory address has not changed, but we cannot use this to determine that the tuple is a variable data type. If we look back and think about it carefully, the definition of a tuple is immutable. We modified the value of the list in the tuple, but because the list is a variable data type, although the value was changed in the list, the address of the list did not change, and the value of the address of the list in the tuple did not change, so means that the tuple has not changed. We can think of tuples as immutable data types because tuples are immutable.
The above is the detailed content of What are the immutable data types in Python?. For more information, please follow other related articles on the PHP Chinese website!