pythonrag

Gary Herron gherron at digipen.edu
Mon Apr 5 11:25:24 EDT 2010


Jason Friedman wrote:
> I saw this posted in the July issue but did not see any follow-up there:
>
> $ 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
>   

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




More information about the Python-list mailing list