Try this in an interactive python shell.
[] is [ ]
The above returns False, why?
Logic Operations Every value in Python is either True or False, numbers are True if they are not zero, and other values are True if they are not empty. e.g. "" and [] are both False.
First, we look at what kind of values evaluate to "True" or "False" in python. Anything that is "empty" usually evaluates to False, along with the integer 0 and the boolean value of False. Objects that are not empty evaluate to "True", along with numbers not equal to 0, and the boolean value True.
You can check if a value is either truthy or falsy with the built-in bool() function. According to the Python Documentation, this function: Returns a Boolean value, i.e. one of True or False .
Use the is not operator to check if a variable is not None in Python, e.g. if my_var is not None: . The is not operator returns True if the values on the left-hand and right-hand sides don't point to the same object (same location in memory).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With