Comparing Integers Caveat
is keyword is used for comparisons, Python compares the objects ids using something like this:
foo = 24
foo = 57
id(foo) == id(bar)
Here’s the caveat: values between -5 and 256 are preallocated.
>>> 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.