Interesting behaviour of the assignment

D-Man dsh8290 at rit.edu
Thu Dec 28 19:46:36 CET 2000


This is not a bug, but rather a side-effect.  Integers in python are
immutable.  For efficiency, at startup the small integers are created.
Then every variable that has such a value is just a reference to the
constant integer created at startup.  This way you don't have
malloc/free calls and ref-counting to handle each time you do

i = 1
i = i + 1


Apparently 99 is the threshold for the integers created at startup and
the integers created upon demand.  I did a few tests of my own:

a = 99
b = 99
a is b
a == b
id( a )
id( b )
# the same object

a = 100
b = 100
a is b
a == b
id( a )
id( b )
# different objects

list = []
list.append( 100 )
list.append( 100 )
list.append( 100 )
for i in list : 
	print id( i )
# note that each element has a different id

list = []
for i in range( 3 ) :
	list[i] = 100
for i in list :
	print id( i )
# each one is the same here


id() returns the id of the object, which is implementation-dependant.
It currently just returns the address of the object.

It appears that the 'is' keyword checks to see if 2 references refer
to the same object while the '==' operator checks to see if the
objects 2 references refer to have the same value.

I would conclude that when the assignment is made in the loop, it is
optimized to be the same actual object (since it is immutable) but
when the assignment is made independently in separate commands the
objects are created independently.

-D


PS.  I would have included the interpreter's output, but I couldn't
find an easy way to do it.  I am using vim as the editor in a remote
login session without the copy-paste features of X.


On Thu, Dec 28, 2000 at 07:25:14PM +0900, June Kim wrote:
> >>> a=100
> >>> b=100
> >>> a is b
> 0
> >>> a=99
> >>> b=99
> >>> a is b
> 1
> 
> Is this an intended/expected result? What is the lying structure beneath
> this?
> 




More information about the Python-list mailing list