Python Truthiness and Truth Table

The table below shows what values are considered equal in the python programming language. I thought I might be able to find more reasons for Why I hate Python, but actually the python truth table is very reasonable. Also, This truth table will help you be confident of what values are considered True or False.

This table demonstrates why it is best practice to use x is None instead of if x == None. None can be equal to any object instance depending on its implementation of __eq__.

This table shows what python values are equal to each other. For example 0 == False.
Python Equality Table

This is a pure and beautiful sight compared to to Javascript or PHP. It is a little surprising to me that [] == [] since I would expect them to be two different list instances, but I would expect equality for (,) = (,) (identical tuples).

There are a few nuances when considering truthiness, however. If you’ve got code that reads if x: ... The following values for x are treated as false:

  • None
  • False
  • zero of any numeric type. Like these: 00L0.00j.
  • any empty string, tuple, or array.  ''()[].
  • an empty dictionary, for example, {}.
  • instances of user-defined classes, if the class defines a __nonzero__() or __len__() method and that method returns the integer 0 or boolean value False

Everything else is truthy (considered equal to True).

This table shows which python values are "truthy" (equal to True) or "falsey" (equal to False).
Python Truthy Table

Here’s the code I used to generate the tables above.

https://gist.github.com/adamloving/714438d7ed1eff231ba2b5e0c6ed2569