Why does “[] is [ ]” evaluate to False in python

前端 未结 4 816
無奈伤痛
無奈伤痛 2020-12-20 18:46

Try this in an interactive python shell.

[] is [ ]

The above returns False, why?

相关标签:
4条回答
  • 2020-12-20 19:16

    You created two mutable objects, then used is to see if those are the same object. That should definitely return False, or something would be broken.

    You wouldn't ever want is to return true here. Imagine if you did this:

    foo = []
    bar = []
    foo.append(42)
    

    then you'd be very surprised if bar now contains 42. If is returned true, meaning that both [] invocations returned the exact same object, then appending to foo would be visible in the reference to bar.

    For immutable objects, it makes sense to cache objects, at which point is may return true, like with empty tuples:

    >>> () is ()  # are these two things the same object?
    True
    

    The CPython implementation has optimised empty tuple creation; you'll always get the exact same object, because that saves memory and makes certain operations faster. Because tuples are immutable, this is entirely safe.

    If you expected to test for value equality instead, then you got the wrong operator. Use the == operator instead:

    >>> [] == []  # do these two objects have the same value?
    True
    
    0 讨论(0)
  • 2020-12-20 19:35

    In python is does a reference equality check like [] and [] they are different objects you can check that by

    print id([]),id([])
    

    or

     In [1]: id([])
    Out[1]: 140464629086976
    
    In [2]: id([])
    Out[2]: 140464628521656
    

    both will return different address and both are different object so is will always give false

    [] is []
    

    output

    false
    
    0 讨论(0)
  • 2020-12-20 19:39

    [] is like list(), if you do this:

    a = list()
    b = list()
    

    clearly a and b are two completly different objects, hence:

    a is b # False
    

    like

    list() is list() # False
    

    like

    [] is [] # False
    
    0 讨论(0)
  • 2020-12-20 19:41

    The == operator compares the values of both the operands and checks for value equality. Whereas is operator checks whether both the operands refer to the same object or not.

    id('') : 139634828889200
    id('') : 139634828889200
    id('') : 139634828889200
    
    id([]) : 139634689473416
    id([]) : 139634689054536
    id([]) : 139634742570824
    
    0 讨论(0)
提交回复
热议问题