Try this in an interactive python shell.
[] is [ ]
The above returns False, why?
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
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
[] 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
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