What is Truthy and Falsy? How is it different from True and False?

We use "truthy" and "falsy" to differentiate from the bool values True and False. A "truthy" value will satisfy the check performed by if or while statements. As explained in the documentation, all values are considered "truthy" except for the following, which are "falsy":

  • None
  • False
  • Numbers that are numerically equal to zero, including:
    • 0
    • 0.0
    • 0j
    • decimal.Decimal(0)
    • fraction.Fraction(0, 1)
  • Empty sequences and collections, including:
    • [] - an empty list
    • {} - an empty dict
    • () - an empty tuple
    • set() - an empty set
    • '' - an empty str
    • b'' - an empty bytes
    • bytearray(b'') - an empty bytearray
    • memoryview(b'') - an empty memoryview
    • an empty range, like range(0)
  • objects for which
    • obj.__bool__() returns False
    • obj.__len__() returns 0, given that obj.__bool__ is undefined

As the comments described, it just refers to values which are evaluated to True or False.

For instance, to see if a list is not empty, instead of checking like this:

if len(my_list) != 0:
   print("Not empty!")

You can simply do this:

if my_list:
   print("Not empty!")

This is because some values, such as empty lists, are considered False when evaluated for a boolean value. Non-empty lists are True.

Similarly for the integer 0, the empty string "", and so on, for False, and non-zero integers, non-empty strings, and so on, for True.

The idea of terms like "truthy" and "falsy" simply refer to those values which are considered True in cases like those described above, and those which are considered False.

For example, an empty list ([]) is considered "falsy", and a non-empty list (for example, [1]) is considered "truthy".

See also this section of the documentation.

Tags:

Python