转载请注明出处:http://blog.csdn.net/sinat_14849739/article/details/78311832
本文出自Shawpoo的专栏
我的简书:简书
【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
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
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
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
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
x = [1, 2, 3]
y = x
print(x == y)
print(x is y)
print(id(x))
print(id(y))
执行结果:
True
True
2539215778568
2539215778568
在上面的例子中,我们分别打印了两种运算符的比较结果和内存地址,所以可以得出:
以上结论只针对对变量直接赋值或变量相互赋值后的比较,不针对两个变量之间拷贝后在进行比较。
后面会补充一篇Python中的浅拷贝和深拷贝。(已更新,Python中的赋值、浅拷贝和深拷贝(含图))
Python的运算符