Python integer caching

后端 未结 2 1015
攒了一身酷
攒了一身酷 2020-12-03 23:02

In the following python script, why the second assert goes through (i.e., when adding 0 to 257 and stores the result in y, then x and y become different objects)? Thanks!

2条回答
  •  醉梦人生
    2020-12-03 23:54

    When you use is, you are checking whether or not the two objects point to the same memory location. If they do, then the result is True. Otherwise, the result is False.

    To check if the values are equivalent, use ==, e.g. assert x == y. Alternatively, to assert that they are not equal, use !=, e.g. assert x != y.

    x = 257
    y = 257
    
    
    >>> id(x)
    4576991320
    
    >>> id(y)
    4542900688
    
    >>> x is y
    False
    
    x = 257
    y = 257 + 0
    
    >>> id(x)
    4576991368
    
    >>> id(y)
    4576991536
    

提交回复
热议问题