python杂记——is和==的区别

python中一切都是对象,is和==是常用来进行对象比较。记录一下两者之间的区别。

==是用来比较两个对象的值是否相等;而is是比较两个对象是不是同一个,也就是指向同一块内存地址。介绍is之前先说一下id函数。id函数是获取对象在生命周期中的标示,一个对象的标示始终是唯一且不变的,也可以将该标示理解为内存地址。
下面通过几个例子来说明一下。

测试环境:Ubuntu18 + python3.7

def test_is_equ():
    a = 9
    b = 9
    print("a == b: ", a == b, "; a is b: ", a is b, "; id(a): ", id(a), "; id(b): ", id(b))
    
    a = 10000
    b = 10000
    print("a == b: ", a == b, "; a is b: ", a is b, "; id(a): ", id(a), "; id(b): ", id(b))
    
    l1 = [1, 2, 3, 4, 5]
    l2 = [1, 2, 3, 4, 5]
    print("l1 == l2: ", l1 == l2, "; l1 is l2: ", l1 is l2, "; id(l1): ", id(l1), "; id(l2): ", id(l2))
    
    a = 1
    b = 2
    print("a == b: ", a == b, "; a is b: ", a is b, "; id(a): ", id(a), "; id(b): ", id(b))
    
    a = b
    print("a == b: ", a == b, "; a is b: ", a is b, "; id(a): ", id(a), "; id(b): ", id(b))
test_is_equ()

测试结果:

a == b:  True ; a is b:  True ; id(a):  94902318789824 ; id(b):  94902318789824
a == b:  True ; a is b:  True ; id(a):  140651975821168 ; id(b):  140651975821168
l1 == l2:  True ; l1 is l2:  False ; id(l1):  140651949194688 ; id(l2):  140651948992704
a == b:  False ; a is b:  False ; id(a):  94902318789568 ; id(b):  94902318789600
a == b:  True ; a is b:  True ; id(a):  94902318789600 ; id(b):  94902318789600

你可能感兴趣的:(Python基础,Python,python)