Search code examples
pythontruthiness

Python truthiness - Different behavior between different checks


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?


Solution

  • 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...