[Tutor] integers are also objects?

Remco Gerlich scarblac@pino.selwerd.nl
Mon, 3 Dec 2001 08:57:37 +0100


On  0, karthik Guru <karthikg@aztec.soft.net> wrote:
> hi all!,
> 
> I'm having a very basic python doubt.
> 
> Are integers objects in python?

Everything is an object.

> d:\>python
> Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license" for more information.
> >>> i = 10
> >>> a = 5+5
> >>> id(a)
> 8136016
> >>> id(i)
> 8136016
> 
> In both cases, i and a, the id of the objects happened to be same though i
> created 2 different integer objects.

In the case of literals of immutable objects, Python sometimes caches some
of them and re-uses the same object. Since they're immutable anyway, this is
no problem. Python caches for instance all integers between -1 and 100, or
some such. Those numbers may be wrong and may change.

Try:
i = 106
a = 106
id(i)
id(a)


> so (i == a) obviously works.
> 
> So my question is that does "==" work on contents in case of integers or it
> works only on
> references and python makes sure that integer references with same content
> point to the
> same location, the way it works for strings.

Not all strings with the same content point to the same location; some of
them are cached, but not all of them. Typically only strings that you use as
literals (the ones you "spell out" in program code) are cached, not strings
that are the result of a computation.

Any == check on any two objects first compares the two references, if
they're the same then the objects are equal (since they're the same object).
Only if they're not the same, are the objects then compared for value.

-- 
Remco Gerlich