Python_Tips[6] -> is 和 == 的区别
is和==的区别 / Difference between is and ==
对于Python的对象来说,具有id/type/value三种特性,而在判断两个相等的is和==中,分别是对对象的id和value进行判断,以下例子可以看出两者的不同之处,
1 x = [1, 2, 3] 2 y = [1, 2, 3] 3 z = x 4 print('x id is %d, y id is %d, z id is %d' % (id(x), id(y), id(z))) 5 # x id is 52275016, y id is 13096648, z id is 52275016 6 7 # is judge by id, == judge by value 8 print(x is y, x==y) # False, True 9 print(x is z, x==z) # True, True
从查看的结果来看,x和y的值相同,但是id却不同,而x和z的值相同,也就是两者指向了同一个对象,分别将y和z与x进行等价比较,结果中可以看出,id相同的x和z的is语句判断成立,而id不同但是值相同的x和y则不成立。
参考链接