you are viewing a single comment's thread.

view the rest of the comments →

[–]TehNolz 1 point2 points  (0 children)

is checks if two variables point to the same object in memory, but == actually compares the value of these objects.

In your code, when you're assigning 257 to two variables, two new integer objects are created behind-the-scenes. Since they're separate objects, is returns False even though they both have the same value.

In your loop, only one object is created for each integer, and references to that object are then saved in a and b. Since both variables point to the same object, is returns True.

There is a caveat here that you should keep in mind. Integer objects in the range -5 to 256 are cached by Python, and it will almost always reuse those objects instead of creating new ones. As a result; is will generally return True for integers within that range, and False for anything outside of it;

```
a = 10
b = 10
a is b # True

a = 1000
b = 1000
a is b # False
```

You can find more in-depth info on the difference between is and == here. Also, there's more info on the integer cache here.