'==' vs. 'is' behavior

Fredrik Lundh fredrik at pythonware.com
Fri Nov 12 10:28:51 EST 1999


Andy Fox <foxes at theriver.com> wrote:
> I thought I understood the difference between the '==' and 'is'
> operators, but just found an exception to the rule.

nope.  no exception.  read on, to understand
why.

> I understand the following:
> >>> a = (1, 2)
> >>> b = (1, 2)
> >>> a == b #are they equivalent?  yes.
> 1
> >>> a is b #are they the same object? no.
> 0
 
> Why doesn't it work for a certain integers:
> >>> a = 2
> >>> b = 2
> >>> a == b #are they equivalent?  yes.
> 1
> >>> a is b #are they the same object? yes.  Why?
> 1

integers are immutable, which means that they
can be shared between variables.  python's integer
implementation happens to preallocate a set of
small integers, to speed things up a little.

but maybe you've missed that variables are just
names?

"a" and "b" happen to point to the same internal
integer object.  if you assign one of them to some-
thing else, you don't change the integer, you just
tell python to bind the name to something else.

in other words, it's perfectly possible to have
many variable names pointing to the same internal
object.

btw, the "id" function gives you a unique identity
for each object:

a = 2
b = 2
print id(a)
print id(b)

prints

8918500
8918500

(or something similar).

and "a is b" is of course the same thing as
"id(a) == id(b)",

> Further experimentation shows that this seems to work for integers
> through 99, but that starting with 100 the results of the 'is' test
> return 0, as I would expect.

python's integer implementation provide ready-made
integers for that range.  nothing strange here, really.

finally, sys.getrefcount allows you to check how many
others that happen to point to any one object:

import sys

for i in xrange(150):
    print i, sys.getrefcount(i)

prints:

0 55
1 40
2 22
3 8
4 14
5 4
6 4
7 5
8 10
9 4
10 3
11 5
12 3
13 3
14 3
15 5
94 3
...
95 3
96 3
97 3
98 3
99 3
100 2
101 2
102 2
103 2
104 2
105 2
...

on my box...  (for "100", there's one reference
from the "i" variable, and one extra introduced
by the getrefcount function itself -- it needs
to hold on to the integer object while deter-
mining the reference count...  if the count is
higher than 2, someone else is also referring
to the same value)

</F>





More information about the Python-list mailing list