Python !=和is not运算符的区别
!=运算符检查被比较的两个对象的值是否相同。另一方面,”is not”运算符检查被比较的两个对象是否不指向同一个引用。如果被比较的对象不指向同一个引用,”is not”运算符返回true,否则返回false。本文将讨论如何使用!=和”is not”运算符以及它们之间的区别。
!= 运算符 | “is not”运算符 |
---|---|
!= 运算符仅比较正在比较的对象的值。 | “is not”运算符比较对象是否指向相同的内存位置。 |
如果两个对象的值不同,则返回 True,否则返回 False。 | 如果对象没有指向相同的内存位置,则返回 true,否则返回 false。 |
!= 运算符的语法是 object1 != object2 | “is not”运算符的语法是 object1 is not object2 |
示例
在下面的示例中,我们使用!=运算符和 “is not” 运算符来比较不同数据类型的两个对象值,比如整数、字符串和列表,以查看这两个运算符之间的差异。
# 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
结论
在本文章中,我们讨论了”!=”运算符和”is not”运算符的区别,以及这两个比较运算符如何用于比较两个对象。”!=”运算符只比较值,而”is not”运算符则检查被比较对象的内存位置。在比较两个对象时,这两个运算符可以在不同的场景中使用。