python '==' 和 'is'

通过一个小例子来看

[root@localhost day1]# python3
Python 3.6.0 (default, Dec 27 2018, 17:19:56) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a=[1,2,3]
>>> b=[1,2,3]
>>> a==b
True
>>> a is b
False
>>> id(a)
140193593394504
>>> id(b)
140193593373640
>>> c=a
>>> c is a
True
>>> id(a)
140193593394504
>>> id(c)
140193593394504
>>> 

在上面我们可以看出 ==是判断两个变量的内容是否相同 而is 则是判断两个变量的内存地址是否相同

但是值得注意 在python中小整数共享内存[-5,257] 如下所示 引用他们地址是相同的

>>> c=100
>>> d=100
>>> c is d
True
>>> id(c)
9309344
>>> id(d)
9309344

猜你喜欢

转载自blog.csdn.net/weixin_38280090/article/details/85282182