469,949 Members | 2,180 Online

# X is confusing

I get this inb the Python interpreter v. 2.3

X=99
X is 99 True Y=100
Y is 100 False

Numbers less that 100 get True, more than 100 get False. It seems. What does
this mean? If nothing, then why does it happen? I mean how do you explain
'is' or 'id(X)' to the first time programmer when it does this to you.

Peter
Jul 18 '05 #1
3 1023
On Tue, Jul 06, 2004 at 09:53:35PM +0100, Peter Mott wrote:
Numbers less that 100 get True, more than 100 get False. It seems. What does
this mean? If nothing, then why does it happen?
Small integer objects are cached to improve performance. It's an
implementation detail so don't count on it.
I mean how do you explain 'is' or 'id(X)' to the first time
programmer when it does this to you.

Use 'is' as it was intended (i.e. to test object identity).

Neil
Jul 18 '05 #2
>> I mean how do you explain 'is' or 'id(X)' to the first time
programmer when it does this to you.

A first time programmer should never need to use 'is', with the exception
of '... is None' (and even that can be replaced by == as far as a first
time programmer is concerned).

An understanding of the meaning of 'is' requires understanding the concept
of objects, and the difference between object equality and object
identity. Once those concepts are known, it should be easy to explain
that since low-valued integers are frequently used, python creates them
once and reuses them when needed, whereas for larger numbers a new object
is created every time.
Jul 18 '05 #3
"Peter Mott" <pe***@monicol.co.uk> wrote in
I get this inb the Python interpreter v. 2.3

X=99
X is 99 True Y=100
Y is 100 False
Numbers less that 100 get True, more than 100 get False. It seems.
What does this mean? If nothing, then why does it happen? I mean how
do you explain 'is' or 'id(X)' to the first time programmer when it
does this to you.

Similar things happen with strings:
x = 'hello'
x is 'hello' True y = 'hello world'
y is 'hello world' False

The compiler is free to optimise immutable values if it wishes. First time
programmers probably don't need to know all of the details of 'is', for
that matter even experienced programmers rarely need to use it.
Jul 18 '05 #4

### This discussion thread is closed

Replies have been disabled for this discussion.