Home  >  Article  >  Backend Development  >  What are the immutable data types in Python?

What are the immutable data types in Python?

anonymity
anonymityOriginal
2019-06-11 11:16:2918356browse

What are the immutable data types in python?

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))
1912499232 <class &#39;int&#39;>
1912499264 <class &#39;int&#39;>

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 = &#39;djx&#39;
print(id(b),type(b))
b = &#39;djx1996&#39;
print(id(b),type(b))
535056476344 <class &#39;str&#39;>
535056476624 <class &#39;str&#39;>

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 = [&#39;1&#39;,&#39;2&#39;]
c = (1,2,c1)
print(c,id(c),type(c))
c1[1] = &#39;djx&#39;
print(c,id(c),type(c))
result:
(1, 2, [&#39;1&#39;, &#39;2&#39;]) 386030735432 <class &#39;tuple&#39;>
(1, 2, [&#39;1&#39;, &#39;djx&#39;]) 386030735432 <class &#39;tuple&#39;>

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn