X is confusing

P

Peter Mott

I get this inb the Python interpreter v. 2.3

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
 
N

Neil Schemenauer

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
 
P

Paramjit Oberoi

I mean how do you explain 'is' or 'id(X)' to the first time
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.
 
D

Duncan Booth

I get this inb the Python interpreter v. 2.3


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:

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top