- 不可变数据类型更改后地址发生变化,可变数据类型更改后地址不发生变化。
- 看代码说话
a = 1 #int
b = "string" #string
c = (1,2) #tuple
print(type(a),id(a))
print(type(b),id(b))
print(type(c),id(c))
a += 1
b += "1"
c += (3,4)
print(a,aid(a))
print(b,id(b))
print(c,id(c))
运行结果如下:
<class ‘int’> 140721425453888
<class ‘str’> 2794250914424
<class ‘tuple’> 2794301510664
2 140721425453920
string1 2794303444504
(1, 2, 3, 4) 2794303362536
a = [1,2] #list
b = {"1":1,"2":2} #dict
c = {1,2} #set
print(type(a),id(a))
print(type(b),id(b))
print(type(c),id(c))
a.append(3)
b[3]="3"
c.add(3)
print(a,id(a))
print(b,id(b))
print(c,id(c))
运行结果如下:
<class ‘list’> 2794303322632
<class ‘dict’> 2794303389200
<class ‘set’> 2794302728904
[1, 2, 3] 2794303322632
{‘1’: 1, ‘2’: 2, 3: ‘3’} 2794303389200
{1, 2, 3} 2794302728904
3.结论
int、string、tuple 是不可变数据类型;
list、dict、set是可变数据类型。