python 中 is, is not ,==, != 的区别
首先说结论:
1、is, is not 对比的是两个变量的内存地址
2、==,!= 对比的是两个变量的值
由此可以进一步推出:
a、假如比较的两个变量,指向的都是地址不可变的类型(str等),那么is,is not 和 ==,!= 是完全等价的。
b、假如对比的两个变量,指向的是地址可变的类型(list,dict,tuple等),则两者是有区别的。
示例:
# python code to differentiate between != and “is not” operator.
# comparing object with integer datatype
a = 10
b = 10
print("comparison with != operator",a != b)
print("comparison with is not operator ", a is not b)
print(id(a), id(b))
# comparing objects with string data type
c = "Python"
d = "Python"
print("comparison with != operator",c != d)
print("comparison with is not operator", c is not d)
print(id(c), id(d))
# comparing list
e = [ 1, 2, 3, 4]
f=[ 1, 2, 3, 4]
print("comparison with != operator",e != f)
print("comparison with is not operator", e is not f)
print(id(e), id(f))
comparison with != operator False
comparison with is not operator False
139927053992464 139927053992464
comparison with != operator False
comparison with is not operator False
139927052823408 139927052823408
comparison with != operator False
comparison with is not operator True
139927054711552 139927052867136
