The result in the two following examples is different:
EXAMPLE 1
a = 845
b = int("8"+"4"+"5")
print(a == b) # True
print(a is b) # False
EXAMPLE 2
a = 845
b = 840+5
print(a == b) # True
print(a is b) # True
How can it be explained? Why in the first case the same integer is kept in two different memory slots in the pile?
I expected the result to be the same (True) in both cases.
>Solution :
Another question provides good context on this issue, but this is a bit different to the cases mentioned there (but it comes down to the same thing in the end). Even though only integers between -5 and 256 are cached and return True for is checks, the same happens for hardcoded integers, since they are compiled as constants and are not allocated.
Using compiler explorer makes this a bit easier to understand. First example can also be written as
a = 845
b = int("845")
print(a == b) # True
print(a is b) # False
We can see in https://godbolt.org/z/zM3haedb9 that string concatenation is done in compile-time, but int is called in the end again, which creates a new integer and since it is not in the cached range, a new object is created, making is return False.
For second example, addition is done in compile team, making it equivalent to
a = 845
b = 845
print(a == b) # True
print(a is b) # True
Which with the help of the other question makes complete sense.
You can check out https://godbolt.org/z/xKacd5oh4 to see that after compilation, both a and b are created the same way.