看了一下网络相关文章,还是决定自己写一下,转载必须注明出处。
以下所有的内容都是基于内存地址来说的。
可变数据类型:变量引用的数据类型,在更改数值的时候,存在不开辟新内存 的行为,此数据类型为可变数据类型。
不可变数据类型 :变量引用的数据类型,在更改数值的时候,不存在不开辟新内存 的行为,此数据类型为不可变数据类型。
在 python 中,strings, tuples, 和 numbers 是不可更改的对象,而 list,dict 等则是可以修改的对象。根据结论,阅读下面解析。
更改值,开辟新内存
代码:
num = 1
print(id(num))
num = 2
print(id(num))
结果:
140706618831104
140706618831136
分析:下图中红色框代表里面的内容不可更改
更改值,开辟新内存
代码:
string = 'a'
print(id(string))
string = 'b'
print(id(string))
结果:
2793695685168
2793695653232
分析:
更改值,不开辟新内存
代码:
list = ['a','b','c','d','e','f','g']
print(id(list))
list[1] = 'w'
print(id(list))
print(list)
结果:
1490101031496
1490101031496
['a', 'w', 'c', 'd', 'e', 'f', 'g']
分析:
更改值,开辟新内存
代码:
list = ['a','b','c','d','e','f','g']
print(id(list))
list = (1,2,3,4,5,6)
print(id(list))
结果:
2123071902280
2123073209064
分析:
更改值,不开辟新内存 ——> 报错,不能修改 ——> 假设不成立
代码:
tup = ('a','b','c','d','e','f','g')
print(id(tup))
tup[1] = 'w'
print(id(tup))
print(tup)
结果:报错
2210815038744
Traceback (most recent call last):
File "E:/pythonTest/test.py", line 3, in
tup[1] = 'w'
TypeError: 'tuple' object does not support item assignment
分析:
更改值,开辟新内存
tup = ('a','b','c','d','e','f','g')
print(id(tup))
tup = (1,2,3,4,5,6)
print(id(tup))
结果:
2444846585112
2444846514920
分析:
同“列表”,略
同“列表”,略