How to create the int 1 at two different memory locations?

后端 未结 3 746
不思量自难忘°
不思量自难忘° 2020-12-10 19:47

I want to show someone how using is instead of == to compare integers can fail. I thought this would work, but it didn\'t:

>>         


        
3条回答
  •  鱼传尺愫
    2020-12-10 20:33

    The following example fails in both Python 2 and 3:

    >>> n=12345
    >>> ((n**8)+1) % (n**4) is 1
    False
    >>> ((n**8)+1) % (n**4) == 1
    True
    

    The reasons are slightly different. Python 2 uses the int type for small integers and the long type for arbitrary precision values. Only the int type is interned so the example fails when a 1L is returned.

    Python 3 only uses the arbitrary precision type (and renamed it to int). The example fails because the remainder calculation internally computes a value of 1 and returns it. The interning check is only done when objects are created and the object was created at the start of the calculation before it had the value 1.

提交回复
热议问题