After reading this and this, I still cannot understand the following behaviour:
a = 1000
b = 1000
print (a == b)
print (a is b)
print (f"id(a) = {id(a)} \nid(b) = {id(b)}")
As expected I get
True
True
id(a) = 2806705928816
id(b) = 2806705928816
But when i try to do something like this:
a = 1000
b = 1000 + a - a
print (a == b)
print (a is b)
print (f"id(a) = {id(a)} \nid(b) = {id(b)}")
I got False
in expression a is b
True
False
id(a) = 3030783801968
id(b) = 3030783802064
Why does a variable behave differently when assigning the result of an expression over a integer and an expression with other variables to it? Although mathematically this gives the same integer.
When you do something like :
(case-1)
a = 1000
b = a
or (case-2)
a = 1000
b = 1000
Python is smart enough to know before hand that even after execution you won't need new memory.
So, python just before execution makes b
an alias of a
in the first case.
The second case is bit different. Python is a true object oriented language, the literal 1000
is treated as an object. (Intuitively you can think as 1000 to be name of a const object).
So in second case a
and b
are technically, both becoming alias
of 1000
Now in your example:
a = 1000
b = 1000 + a - a
print (a == b)
print (a is b)
while assignment of b
, python doesn't know before hand what is going to be the value of a
. When I say before-hand I mean before any form of calculation being started. So python reserves a new memory location for b
and then saves the output of the operation in this new memory location.
It is also worth noting this:
4-1 is 3
True
In this case, python doesn't saves this line with 4-1
but processes it before compilation to be 3
, for runtime optimisation.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments