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