When is the `==` operator not equivalent to the `is` operator? (Python)

前端 未结 4 1405
有刺的猬
有刺的猬 2020-12-03 17:58

I noticed I can use the == operator to compare all the native data types (integers, strings, booleans, floating point numbers etc) and also lists, tuples, sets

4条回答
  •  悲哀的现实
    2020-12-03 18:12

    The == does more than comparing identity when ints are involved. It doesn't just check that the two ints are the same object; it actually ensures their values match. Consider:

    >>> x=10000
    >>> y=10000
    >>> x==y,x is y
    (True, False)
    >>> del x
    >>> del y
    >>> x=10000
    >>> y=x
    >>> x==y,x is y
    (True, True)
    

    The "standard" Python implementation does some stuff behind the scenes for small ints, so when testing with small values you may get something different. Compare this to the equivalent 10000 case:

    >>> del y
    >>> del x
    >>> x=1
    >>> y=1
    >>> x==y,x is y
    (True, True)
    

提交回复
热议问题