Python學習筆記(七)—Python中is和==(is not和!=)的區別

轉載請注明出處:http://www.lxweimin.com/p/7e51f9cc3c85
本文出自Shawpoo的簡書
我的博客:CSDN博客

【Python學習筆記專欄】:http://blog.csdn.net/column/details/17658.html

Python中有很多種運算符,本文主要記錄一下is==這兩種運算符的區別:

id()函數是查看該對象所在內存地址。每個對象都有對應的內存地址,如:

>>> id(1)
1543816880
>>> id("abc")
2880674151480
>>> id([1, 2, 3])
2880703493384

is 用于判斷兩個變量引用對象是否為同一個, == 用于判斷引用變量的值是否相等。類似于Java中的equal()和==。反之,is not 用于判斷兩個變量是否引用自不同的對象,而 != 用于判斷引用變量的值是否不等。

下面來幾個具體的例子:

  • 整數的比較:
x = 5
y = 5
print(x == y)
print(x is y)
print(id(x))
print(id(y))

執行結果:
True
True
1543817008
1543817008
  • 字符串的比較:
x = "abc"
y = "abc"
print(x == y)
print(x is y)
print(id(x))
print(id(y))

執行結果:
True
True
2039623802136
2039623802136
  • list(列表)的比較:
x = [1, 2, 3]
y = [1, 2, 3]
print(x == y)
print(x is y)
print(id(x))
print(id(y))

執行結果:
True
False
2194144817928
2194144817288
  • tuple(元組)的比較:
x = (1, 2, 3)
y = (1, 2, 3)
print(x == y)
print(x is y)
print(id(x))
print(id(y))

執行結果:
True
False
2699216284336
2699216284480
  • dict(字典)的比較:
x = {"id": 1, "name": "Tom", "age": 18}
y = {"id": 1, "name": "Tom", "age": 18}
print(x == y)
print(x is y)
print(id(x))
print(id(y))

執行結果:
True
False
3005783112296
3005783112368
  • set(集合)的比較:
x = set([1, 2, 3])
y = set([1, 2, 3])
print(x == y)
print(x is y)
print(id(x))
print(id(y))

執行結果:
True
False
2206005855176
2206006414696
  • 賦值后比較(符合所有數據類型),以list為例:
x = [1, 2, 3]
y = x
print(x == y)
print(x is y)
print(id(x))
print(id(y))

執行結果:
True
True
2539215778568
2539215778568 

總結

在上面的例子中,我們分別打印了兩種運算符的比較結果和內存地址,所以可以得出:

  • 只要各對象的值一樣,則 x == y 的值一定為True;
  • 如果對象的類型為整數或字符串且值一樣,則 x == y和 x is y 的值為True。(經測試浮點型數值,只有正浮點數符合這條規律,負浮點數不符合);
  • list,tuple,dict,set值一樣的話,x is y 則為False;
  • x == y 與 x != y 的值相反,x is y 與 x is not y 的值相反。

以上結論只針對對變量直接賦值或變量相互賦值后的比較,不針對兩個變量之間拷貝后在進行比較。

后面會補充一篇Python中的淺拷貝和深拷貝。(已更新Python中的賦值、淺拷貝和深拷貝(含圖))

其他閱讀

Python的運算符

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容