3
number=26
for n in range(101):
    if n is number:
        print(n, "This is the magic number")
        break
    else:
        print(n)

The above code runs perfectly, but when I change the variable and the range, as below, it does not work properly.

number=260
for n in range(300):
    if n is number:
        print(n, "This is the magic number")
        break
    else:
        print(n)
ryanjdillon
  • 17,658
  • 9
  • 85
  • 110
Joe Le Rip
  • 31
  • 1
  • That's not a particularly good duplicate; it explains why the second fails, but no explanation why the first does not. – chepner Aug 22 '16 at 15:45

1 Answers1

4

In general, x == y being True does not guarantee that x is y is also True. Your first code takes advantage of a particular optimization in CPython where small integers (between -5 and 257) are pre-allocated, so that any use of such an integer always uses the same object.

In general, you should never assume that literals will refer to the same object. The interpreter is free to allocate a new object for each use of a literal.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • 1
    Excellent answer. Just to build on it, I thought I would explain the difference between the 'is' and '==' operator. When you ask whether 'a == b', you are querying whether the value of a is equivalent to the value of b whereas when you ask whether 'a is b', you are asking whether a and b are the same thing (from the Python interpreter's perspective i.e. are a and b two different names pointing to the same thing in memory). Also see [here](http://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is-in-python). – gowrath Aug 22 '16 at 15:47
  • 1
    I give the benefit of the doubt to the asker that they already know the difference between `==` and `is` (since it doesn't take much research to discover). It's reasonable to assume that a literal always refers to the same object, but that is not the case in Python. – chepner Aug 22 '16 at 15:55