$ python
Python 2.6.4 (r264:75706, Dec 7 2009, 18:43:55)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 500
>>> b = 500
>>> a == b
True
>>> a is b
False
>>> p = 50
>>> q = 50
>>> p == q
True
>>> p is q
True
>>>
LOL
This topic shows here every 3 weeks or so...
The short of it: CPython optimizes small integers. It's a feature.
Don't rely on it (Google for the rest).
-a
I fail to see the fun?
Remember that everything in Python is an object, even integers.
For integers, I believe Python creates the first 100 integer objects and reuses them.
Larger integers are created when needed, and are different objects.
The example also shows why it usually is wrong to use object comparison ('is') when you
really mean equality (==).
-irmen
In
a=500
b=500
Python could either:
* create two integers containing 500, one for each variable
* create one integer referred to by both variables
The first option will evaluate "a is b" as False, while the second will
evaluate "a is b" as True.
In other words, the "is" operator asks something about storage
location. *WHY* would you care how the integers are stored? It is
considered a *bug* on your part to write a program that depends on the
particular storage option Python chooses for any particular integer.
The second option is more efficient in memory usage, but requires some
run-time to implement, while the first option does not require the
run-time tracking of already-used integers, but may result in more
memory usage. Python, the language, does not specify which storage
option will be used. Python, the C implementation, does both, choosing
the second option for small integers (those less 100 last time I checked).
Gary Herron
--
Gary Herron, PhD.
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418