"""
is和 ==的区别
"""
a = 'abc'
b = 'abc'
print("都是字符串-a is b--", a is b)
print("都是字符串-a == b--", a == b)
c = 11
d = 11
print("都是数字-c is d--", c is d)
print("都是数字-c == d--", c == d)
e = [0, 1, 2]
f = [0, 1, 2]
print("都是列表-e is f--", e is f)
print("都是列表-e == f--", e == f)
g = h = [0, 1, 2]
print("都是列表-g is f--", g is h)
print("都是列表-g == f--", g == h)
i = (0, 1, 2)
j = (0, 1, 2)
print("都是元祖-i is j--", i is j)
print("都是元祖-i == j--", i == j)
k = {"name": "张三"}
m = {"name": "张三"}
print("都是字典-k is m--", k is m)
print("都是字典-k == m--", k == m)
print("a的id--", id(a))
print("b的id--", id(b))
print("c的id--", id(c))
print("d的id--", id(d))
print("e的id--", id(e))
print("f的id--", id(f))
print("g的id--", id(g))
print("h的id--", id(h))
print("i的id--", id(i))
print("j的id--", id(j))
print("k的id--", id(k))
print("m的id--", id(m))
输出结果:
image.png
总结:is是判断id是否相等,==是判断数据是否相等,如果两个变量的值是字符串,数字,元祖,那么is和==的结果无区别。如果是列表和字典,is是false,==是true,特例 g = h = [0, 1, 2]这样的列表,is也是true,因为指向同一空间地址