+ 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

https://code.sololearn.com/cIoZ0Pgk2Xrx/?ref=app

30th Aug 2022, 7:21 AM
ToM
9 odpowiedzi
+ 10
ToM , i have added some comments to your code. just run it and read the explanations: https://code.sololearn.com/cdH39l052Rfl/?ref=app
30th Aug 2022, 10:55 AM
Lothar
Lothar - avatar
+ 5
thanks! Bob_Li
31st Aug 2022, 7:56 AM
Sandeep
Sandeep - avatar
+ 4
Bob_Li why range [-5, 256] ?
30th Aug 2022, 5:23 PM
Sandeep
Sandeep - avatar
+ 4
Bob_Li i don't have realpython subscription. any other source?
30th Aug 2022, 5:53 PM
Sandeep
Sandeep - avatar
+ 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))
30th Aug 2022, 1:22 PM
Bob_Li
Bob_Li - avatar
+ 2
Sandeep I was also curious about this, and it seems to be for performance optimization. https://realpython.com/lessons/small-integer-caching/
30th Aug 2022, 5:42 PM
Bob_Li
Bob_Li - avatar
+ 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
30th Aug 2022, 10:26 PM
Bob_Li
Bob_Li - avatar
0
Mr Tom I think you have in Erorr in you're code a = 200 b = 200 if a == b: print ('a = b')
31st Aug 2022, 9:03 PM
Youssef Hakki
Youssef Hakki - avatar