Understanding Python's “is” operator

前端 未结 11 2290
别那么骄傲
别那么骄傲 2020-11-21 22:42

The is operator does not match the values of the variables, but the instances themselves.

What does it really mean?

11条回答
  •  遇见更好的自我
    2020-11-21 23:06

    A simple example with fruits

    fruitlist = [" apple ", " banana ", " cherry ", " durian "]
    newfruitlist = fruitlist
    verynewfruitlist = fruitlist [:]
    print ( fruitlist is newfruitlist )
    print ( fruitlist is verynewfruitlist )
    print ( newfruitlist is verynewfruitlist )
    

    Output:

    True
    False
    False
    

    If you try

    fruitlist = [" apple ", " banana ", " cherry ", " durian "]
    newfruitlist = fruitlist
    verynewfruitlist = fruitlist [:]
    print ( fruitlist == newfruitlist )
    print ( fruitlist == verynewfruitlist )
    print ( newfruitlist == verynewfruitlist )
    

    The output is different:

    True
    True
    True
    

    That's because the == operator compares just the content of the variable. To compare the identities of 2 variable use the is operator

    To print the identification number:

    print ( id( variable ) )
    

提交回复
热议问题