今天学习天池pythontask中注意到的:
1.is, is not 对比的是两个变量的内存地址
2.==, != 对比的是两个变量的值
3.比较的两个变量,指向的都是地址不可变的类型(str等),那么is,is not 和 ==,!= 是完全等价的。
4.对比的两个变量,指向的是地址可变的类型(list,dict,tuple等),则两者是有区别的。
下面举两个例子:
一、比较的两个变量均指向不可变类型
str1 = "hello"
str2 = "hello"
print(str1 is str2, str1 == str2) # True True
print(str1 is not str2, str1 != str2) # False False
运行结果:
True True
False False
二、比较的两个变量均指向可变类型
dic1 = ["hello"]
dic2 = ["hello"]
print(dic1 is dic2, dic1 == dic2) # False True
print(dic2 is not dic2, dic1 != dic2) # True False
运行结果:
False True
True False