I was quite surprised when
[] is not []
evaluated to True
.
What is happening in this code? What really not
and is
statements are doing?
I was quite surprised when
[] is not []
evaluated to True
.
What is happening in this code? What really not
and is
statements are doing?
a is not b
is a special operator which is equivalent to not a is b
.
The operator a is b
returns True if a and b are bound to the same object, otherwise False. When you create two empty lists you get two different objects, so is
returns False (and therefore is not
returns True).
is
is the identity comparison.
==
is the equality comparison.
Your statement is making two different lists and checking if they are the same instance, which they are not. If you use ==
it will return true and because they are both empty lists.
is checks for identity. []
and []
are two different (but equivalent) lists. If you want to check if both the lists are empty you can use their truth value (false for empty strings, collections, and zeros).
if not ([] and []):
print 'Spanish Inquisition'
the only time that is
is guaranteed to return True is for singletons such as None. Like the Highlander, there can be only one instance of None in your program - every time you return None it's the very same "thing" as the none referred to if you type print None
.
[], OTOH, is not guaranteed to be anything except an empty list and evaluate to False in a boolean context.
The best way to describe WHY that happens is this:
Here is your example
>>> x = []
>>> y = []
>>> print(x is y)
... False
x
and y
are actually two different lists, so if you add something to x
, it does not appear in y
>>> x.append(1)
>>> print(x)
... [1]
>>> print(y)
... []
So how do we make (x is y
) evaluate true?
>>> x = []
>>> y = x
>>> print(x is y)
... True
>>> x.append(10)
>>> print(x)
... [10]
>>> print(y)
... [10]
>>> print(x is y)
... True
if you want to see if two lists have the same contents...
>>> x = []
>>> y = []
>>> print(x == y)
... True
>>> x.append(21)
>>> print(x)
... [21]
>>> print(y)
... []
>>> print(x == y)
... False
>>> y = [21]
>>> print(x == y)
... True