-1

Basically this question is pertraining to a Reddit Post. The function shouldn't be returning True mathematically. But -7 as mentioned in the comment's return's True surprisingly. Can anyone explain why -7 specifically? I'm using python 3.7.

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

check(-7)
True
Bharath M Shetty
  • 30,075
  • 6
  • 57
  • 108
  • Python allocates integer in following way: https://www.laurentluce.com/posts/python-integer-objects-implementation/ So basically, every python program has allocated integers from -7 to 257 ``` #define NSMALLPOSINTS 257 #define NSMALLNEGINTS 5 ``` Since `is` operator checks reference to objects, then you can do trick like: ```python >>>a = 1 >>>b = 1 >>>a is b True >>>a = 300 >>>b = 300 >>>a is b False ``` In order to make your function correct you should use `==` instead of `is`. – Maciej M Jul 30 '19 at 09:15
  • 2
    The answer is also well explained in reddit. – BlueSheepToken Jul 30 '19 at 09:16
  • 2
    @BlueSheepToken I agree. SO is more popular in terms of programming questions. So keeping it here so more people can see and learn something more. – Bharath M Shetty Jul 30 '19 at 09:21
  • @BharathM great point ! – BlueSheepToken Jul 30 '19 at 09:28

1 Answers1

3

Python's is operator checks for identity, not for equality:

In [670]: id(-6), id(-6)
Out[670]: (9830796528, 4454912496)

In [671]: -6 == -6
Out[671]: True

https://docs.python.org/3.3/library/stdtypes.html#comparisons

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105