When the is keyword is used for comparisons, Python compares the objects ids using something like this:

1
2
3
foo = 24
foo = 57
id(foo) == id(bar)

Here’s the caveat: values between -5 and 256 are preallocated.

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> foo = 25
>>> bar = 25
>>> foo == bar
True
>>> foo is bar
True

>>> foo = 257
>>> foo = 257
>>> foo == bar
True
>>> foo is bar
False

So only use is for comparing integers if you’re certain that the values are between -5 and 256. In my opinion, you shouldn’t use is for comparing integers at all. Even though you may be certain when to use it properly, others might not. More importantly readability is sacrificed and might lead to confusion with newcomers to the codebase.