小数据池、is 和 ==的区别
小数据池,在一定情况下出现内存共享(只有int 和 str 才有的)
is 和 ==的区别
id() 打印数据的地址
a = 'hello'
b = 'hello'
print(a == b) 返回True 比较的是数值
print(a is b) 返回False 比较的是地址,看地址方法 print(id(a), id(b))
int类型中 -5 ~ 256之间的数 相同的数全都指向一个内存空间。
字符串中如果有特殊字符他们的内存地址就不一样
字符串中单个*20以内他们的内存地址一样,单个*21以上内存地址不一致
a = 'A' * 20 ; b = 'A' * 20 a is b ==>True
str类型 单个字符乘以20以内的数字都在同一内存地址;只要字符串含有数字那就不共用内存,不会出现小数据池
a = 'alex@' a1 = 'alex@' print(a is a1) # Fales n = 5//2 n1 = 2 print(n is n1) #True
'@' is '@' #True
a = 'a'*21 b = 'a'*21 print(a is b) # Fales a = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' b = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' print(a is b) #True n = -6 n1 = -6 print(n is n1) #False n = -5 n1 = -5 print(n is n1) #True n = 257 n1 = 257 print(n is n1) #True # 列表 li =[1,2,3] li2 =[1,2,3] print(li is li2) #False # 元组 tu =(1,2,3) tu1 =(1,2,3) print(tu is tu1) # False # 字典 dic1 = {'name':'alex'} dic = {'name':'alex'} print(dic1 is dic) #False