不废话,直接上结论:
== 比较操作符:用来比较两个对象值是否相等。 (见例1)
is 同一性运算符:比较两个对象的id值是否相等,即是否是同一对象,是否指向同一个内存地址。(见例2)
补充:当两个对象值相同时,只有其为数值型或字符串型,a is b才为True,当a和b是tuple,list,dict或set型时,a is b为False 。(见例3)
详解:
Python中对象包含的三个基本要素,分别是:id(身份标识)、type(数据类型)和value(值)。
例1.
>>> a = 'cheesezh'
>>> b = 'cheesezh'
>>> a == b
True
例2.
>>> x = y = [4,5,6]
>>> z = [4,5,6]
>>> x == y
True
>>> x == z
True
>>> x is y
True
>>> x is z
False
>>>
>>> print(id(x))
3075326572
>>> print(id(y))
3075326572
>>> print(id(z))
3075328140
例3.
>>> a = 1 # a和b为数值类型
>>> b = 1
>>> a is b
True
>>> id(a)
14318944
>>> id(b)
14318944
>>> a = 'cheesezh' # a和b为字符串类型
>>> b = 'cheesezh'
>>> a is b
True
>>> id(a)
42111872
>>> id(b)
42111872
>>> a = (1,2,3) # a和b为元组类型
>>> b = (1,2,3)
>>> a is b
False
>>> id(a)
15001280
>>> id(b)
14790408
>>> a = [1,2,3] # a和b为list类型
>>> b = [1,2,3]
>>> a is b
False
>>> id(a)
42091624
>>> id(b)
42082016
>>> a = {'cheese':1,'zh':2} # a和b为dict类型
>>> b = {'cheese':1,'zh':2}
>>> a is b
False
>>> id(a)
42101616
>>> id(b)
42098736
>>> a = set([1,2,3])# a和b为set类型
>>> b = set([1,2,3])
>>> a is b
False
>>> id(a)
14819976
>>> id(b)
14822256