+ 2
a = b = 500 print(a is b) a -= 200 b -= 200 print(a is b) a = a - 200 b = b - 200 print(a is b) # explain it
9 Answers
+ 10
ToM ,
i have added some comments to your code. just run it and read the explanations:
https://code.sololearn.com/cdH39l052Rfl/?ref=app
+ 5
thanks! Bob_Li
+ 4
Bob_Li
why range [-5, 256] ?
+ 4
Bob_Li i don't have realpython subscription. any other source?
+ 2
Python caches the integers in the range [-5 , 256] .
https://stackoverflow.com/questions/31830992/is-the-id-of-a-variable-associated-to-the-value-assigned-to-it-after-the-var
+ 2
'''
True for -5 to 256.
Python tries to assign the same id() for these numbers.
Above and below is False
'''
a = b = 0
is_true = []
for i in range(-300,300):
a += i
b += i
if (a is b):
is_true.append(i)
a = b = 0 #reset
print(max(is_true))
print(min(is_true))
+ 2
Sandeep
I was also curious about this, and it seems to be for performance optimization.
https://realpython.com/lessons/small-integer-caching/
+ 2
Sandeep
People at Stackoverflow are generally very knowledgeable, and the replies are very detailed. The takeaway is the -5~256 value is usually but not always cached (second link)
https://stackoverflow.com/questions/306313/is-operator-behaves-unexpectedly-with-integers
https://stackoverflow.com/questions/15171695/whats-with-the-integer-cache-maintained-by-the-interpreter
0
Mr Tom I think you have in Erorr in you're code a = 200
b = 200
if a == b:
print ('a = b')