jawahar jawahar - 1 month ago 12
Python Question

Comparing of two big int must not same but it is diffrent python3

>>>s1 = 100
>>>s2 = 100
>>>s1 is s2
True
>>>b1 = 257
>>>b2 = 257
>>>
>>>b11 = b12 = 257
>>>b1 is b2
False
>>>
>>>b11 is b12
True
>>>


b1 and b2 is
False
because of
PyLongtObject
what happen on b11 and b12?
any idea please help me.

Answer

It's a (convoluted) duplicate of About the changing id of a Python immutable string.

During evaluation phase in REPL loop only one constant with value 257 is created in memory.

compile("a = b = 257", '<stdin>', 'single').co_consts  # (257, None)

When executing, same object (with same address in memory) is assigned to both names.

>>> dis.dis(compile("a = b = 257", '<stdin>', 'single'))
  1           0 LOAD_CONST               0 (257)
              3 DUP_TOP             
              4 STORE_NAME               0 (a)
              7 STORE_NAME               1 (b)
             10 LOAD_CONST               1 (None)
             13 RETURN_VALUE        

Since both names point to same object, it's expected that id on those objects returns same number, therefore is returns True.