Strange Python behavior from inappropriate usage of 'is not' comparison?

后端 未结 5 807
南方客
南方客 2021-01-22 15:12

I (incorrectly?) used \'is not\' in a comparison and found this curious behavior:

>>> a = 256
>>> b = int(\'256\')
>>> c = 300
>>         


        
5条回答
  •  -上瘾入骨i
    2021-01-22 16:12

    Int is an object in python, and python caches small integer between [-5,256] by default, so where you use int in [-5,256], they are identical.

    a = 256
    b = 256
    
    a is b # True
    

    If you declare two integers not in [-5,256], python will create two objects which are not the same(though they have the same value).

    a = 257
    b = 257
    
    a is b # False
    

    In your case, using != instead to compare the value is the right way.

    a = 257
    b = 257
    
    a != b # False
    

提交回复
热议问题