[Tutor] Need some clarification on this

Hugo Arts hugo.yoshi at gmail.com
Sat Mar 19 16:50:16 CET 2011


2011/3/19 Yaşar Arabacı <yasar11732 at gmail.com>:
>>>>a=5
>>>>b=5
>>>>a == b
> True
>>>>a is b
> True
>
> My question is, why "a is b" is true. What I expected it to be is that, a
> and b are different things with same value.
>

It's an optimization thing. When you type "a=5," the python
interpreter is obligated to give you an integer object with the value
5. However, it doesn't need to be a *new* object. If an interpreter
happens to have an object like that lying around already, it is
perfectly allowed to give you that one.

This doesn't mess things up for anyone, because integers are
immutable. You can't change them, so it's safe to give the same object
to different people. Interpreters can make the same optimization for
strings, if they like. It makes it more efficient (since they don't
have to allocate a new object) without changing the semantics of the
language.


More information about the Tutor mailing list