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” 运算符检查被比较对象的内存位置。这两个运算符都可以在比较两个对象的不同场景中使用。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP