[Python]"is"和"=="以及一个新发现

is是判断地址相同,==是判断值相同


a=1

b=a

print(b is a)#True

print(a is b)#True

print(b == a)#True

print('\n')


c=1

d=1

print(d is c)#True#why?

print(c is d)#True

print(c == d)#True

print('\n')


e=1

f=2

print(e is f)#False

print(f is e)#False

print(e == f)#False

print('\n')


g=[1]

h=[1]

print(h is g)#False

print(g is h)#False

print(g == h)#True

print('\n')


i=[1]

j=i

print(i is j)#True

print(j is i)#True

print(i == j)#True

print('\n')



'''answer for why: Python会对比较小的对象缓存,下次用到比较小的对象时,会去缓存区查找,如果找到,不会再开辟新的内存,而是继续把小对象的地址赋给新的值'''

你可能感兴趣的:([Python]"is"和"=="以及一个新发现)