-2

In the following code :

magicnumber = 256
for n in range (500):
    if n is magicnumber:
        print ("the magic number is " , n)
        break
    else:
        print(n)

The loop breaks at 256, but if you set magicnumber to 257, it doesn't. Why ?

gus3000
  • 27
  • 5
TheOraclePhD
  • 83
  • 1
  • 8

1 Answers1

6

Because you are checking for identity with is (instead of checking for equality with ==).

As an implementation detail, Python keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object.

So integers above 256 will still be equal, but not identical (unless they refer to the same object, you can compare that with id()).

Source: https://docs.python.org/3/c-api/long.html#c.PyLong_FromLong

Mike Scotty
  • 10,530
  • 5
  • 38
  • 50