是比较 id 但 id 在 -5 和 256 之间应该是相同的,为什么 x = 3 和 y = 5 不一样?

is compare id but id should be the same between -5 and 256, how come it's not if x = 3 and y = 5?

a = 10 # range -5 to 256
b = 10 # range -5 to 256
print(id(a))
print(id(b))
print(a is b)

# OK THAT'S FINE 

但是

a = 10 # range -5 to 256
b = 10 # range -5 to 256
print(id(a))
print(id(b)) # same memory adress
print(a is b)

# That's working

c = 3 # range -5 to 256
d = 5 # range -5 to 256
print(id(c))
print(id(d)) 
print(c is d) 

不同的内存地址O_o 错误,因为...该范围应该没问题!

看下图,你应该明白为什么了:

  • a is b 为真
  • c is d 为假

-5 到 256 之间的数字

为什么:

  • e is f 为假

对于这个特殊范围之外的其他号码