I went through Truthiness in Python and understood that []
and similar empty objects are interpreted as False
in Python.
But when I type in the following in REPL, it returns False
:
>>> [] == False
False
How is this possible?
I went through Truthiness in Python and understood that []
and similar empty objects are interpreted as False
in Python.
But when I type in the following in REPL, it returns False
:
>>> [] == False
False
How is this possible?
Because ==
doesn't check truthiness, it checks equality. Those two objects are of different types, so they are not equal.
If you want to explicitly see the truthiness of an object, convert it to bool:
>>> bool([])
False
Note you would never do this in real code, because the point of truthiness is that the conversion is implict. Rather, you would do:
if my_value:
...do something...
because == returns equality if the object equals to other...
in this case [] isnt None just an empty array e.g.:
if variable:
print "true"
else:
print "false"
if variable is empty string ('')or empty array ([]) this prints out false.
if variable == None:
print "true"
else:
print "false"
if variable is empty string ('') or empty array ([]) this prints out fasle, because its not None type (its type equals str or list).
==: returns True if 2 variables are equal
if : returns True if variable is not None and ist not empty instance (like empty array or string)