Lessons · Python · why 256 is 256
Why 'is' flickers on numbers
Python keeps one shared copy of small integers, so a is b can be True for 5 and False for 5000. It is an implementation detail, not a rule.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Code that compares numbers with is passes every test on small values and fails in production on large ids. The bug is invisible until the data grows.
How to think about it
Compare values with ==, always. Reserve is for None and for deliberate 'same object' checks. If a test only passes for small numbers, look for an is.
Worked example
a = 5A small int.
b = 5The same shared object, as it happens.
print(a == b, a is b)True True: small ints are shared.
x = int("1000000")A large int built at run time.y = int("1000000")Another one.print(x == y)True: the question that matters.
print(x is y)False: two objects with the same value. Never rely on either answer.
Your turn
Are the two counts equal?
same = n1 n2
Solve one with the tests running
The trap
Modern Python warns about x is 5 ('is' with a literal) because it is almost always wrong; treat the warning as an error.
Practise why 256 is 256 on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.