Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"is" comparison of numbers [duplicate]

Tags:

python

I was given a Python test and one of the questions was: what should be passed to the following function, so that it will return True?

def fun(x):
    if x + 1 is 1 + x:
        return False
    if x + 2 is not 2 + x:
        return False
    return True

In my opinion this doesn't make much sense but I just would like to know the right answer (if such answer exists).

like image 214
nmospan Avatar asked Dec 18 '22 12:12

nmospan


1 Answers

This has to do with how python caches small numbers: https://stackoverflow.com/a/48120163/13003236

Typically, is is used to check if two variables are the same object instead of if they have the same value. However, because of how python caches small numbers, calling is on numbers from -5 to 256 has the same effect as comparing them. So, this function returns true if x + 1 is less than -5, but x + 2 is greater than or equal to -5. That means that passing -7 into this function will cause it to succeed.

like image 153
Simon Shkolnik Avatar answered Jan 06 '23 13:01

Simon Shkolnik