Python中,is==的区别?

我们一共讨论3个字符格式

  • str
  • list
  • pd.DataFrame
In [37]:
a = "Hello world!"
b = "Hello world!"
print type(a)
print a is b
print a == b
<type 'str'>
False
True
In [38]:
a = [1,2,3]
b = [1,2,3]
print type(a)
print a is b
print a == b
<type 'list'>
False
True
In [39]:
import pandas as pd
a = pd.DataFrame({"x": [1,2,3]})
b = pd.DataFrame({"x": [1,2,3]})
print type(a)
print a is b
print a == b
<class 'pandas.core.frame.DataFrame'>
False
      x
0  True
1  True
2  True

我们发现a == b都是True,但是a is b都是False

我们再看一组例子。

In [40]:
a = "Hello world!"
b = a
print type(a)
print a is b
print a == b
<type 'str'>
True
True
In [41]:
a = [1,2,3]
b = a
print type(a)
print a is b 
print a == b 
<type 'list'>
True
True
In [42]:
a = pd.DataFrame({"x": [1,2,3]})
b = a
print type(a) 
print a is b 
print a == b 
<class 'pandas.core.frame.DataFrame'>
True
      x
0  True
1  True
2  True

我们发现直接将b = a后,a is b才会True

这里的区别是,

  • a is b$\to$id(a) == id(b) $\to$ ab相同

  • a == b$\to$a.__eq(b)__ $\to$ ab相等而已

In [43]:
a = "Hello world!"
b = "Hello world!"
print type(a)
print a is b
print a == b
print id(a) == id(b)
print id(a)
print id(b)
<type 'str'>
False
True
False
170150336
170150096
In [44]:
a = [1,2,3]
b = [1,2,3]
print type(a)
print a is b
print a == b
print id(a) == id(b)
print id(a)
print id(b)
<type 'list'>
False
True
False
169902024
169900040
In [45]:
a = pd.DataFrame({"x": [1,2,3]})
b = pd.DataFrame({"x": [1,2,3]})
print type(a)
print a is b
print a == b
print id(a) == id(b)
print id(a)
print id(b)
<class 'pandas.core.frame.DataFrame'>
False
      x
0  True
1  True
2  True
False
169895752
169895696

这里我们会发现,虽然相等,但是相同的原因是,ab的内存地址不同。

但是这里有一个意外,

In [46]:
a = "Hello"
b = "Hello"
print type(a)
print a is b
print a == b
print id(a) == id(b)
print id(a)
print id(b)
<type 'str'>
True
True
True
169983672
169983672

当处理单一字符串的时候,ab会共用一个内存地址,因此这也是python快捷的原因之一。