I am trying to study assignment in python I was confused by this.
>>> a=343434;b=343434
>>> a is b
True
>>> a=343434
>>> b=343434
>>> a is b
False
I am trying to study assignment in python I was confused by this.
>>> a=343434;b=343434
>>> a is b
True
>>> a=343434
>>> b=343434
>>> a is b
False
The Python interpreter is smart. In the first line, it can see the definition of both a
and b
and the assignment at the same time, so it 'thinks': "man, I can make them point to the same location to save memory", and so it does. It can optimize your code for memory usage.
In the second case, it allocates memory as soon as it sees the definitions. It 'thinks': "hey, I've got a definition here! Let me allocate some memory!", and so it does. It cannot optimize your code for memory usage here.
That's why these objects are not the same.
This works only in 'live mode' (when you're inserting commands into the interpreter and it deals with them right away). If you put
a=343434
b=343434
print a is b
into a file (say, test.py
) and then run python test.py
, it will output True
(at least in Python 2.7.10), because, as in the first case, it can see the whole code at once and perform some optimizations.