Wednesday, November 1, 2023

Truthy and Falsy Values in Python

In Python, individual values can evaluate to either True or False. They do not necessarily have to be part of a larger expression to evaluate to a truth value because they already have one that has been determined by the rules of the Python language.

The basic rules are:

  • Values that evaluate to False are considered Falsy.
  • Values that evaluate to True are considered Truthy.

According to the Python Documentation:

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below (and, or, not).

Boolean Context

When we use a value as part of a larger expression, or as an if or while condition, we are using it in a boolean context.

You can think of a boolean context as a particular "part" of your code that requires a value to be either True or False to make sense. 

Falsy Values

Sequences and Collections:

  • Empty lists []
  • Empty tuples ()
  • Empty dictionaries {}
  • Empty sets set()
  • Empty strings ""
  • Empty ranges range(0)

Numbers

  • Zero of any numeric type.
  • Integer: 0
  • Float: 0.0
  • Complex: 0j

Constants

  • None
  • False

Falsy values were the reason why there was no output in our initial example when the value of a was zero.

Truthy Values

According to the Python Documentation:

By default, an object is considered true.

Truthy values include:

  • Non-empty sequences or collections (lists, tuples, strings, dictionaries, sets).
  • Numeric values that are not zero.
  • True

The Built-in bool() Function

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. x (the argument) is converted using the standard truth testing procedure.
>>> bool(5)
True
>>> bool(0)
False
>>> bool([])
False
>>> bool({5, 5})
True
>>> bool(-5)
True
>>> bool(0.0)
False
>>> bool(None)
False
>>> bool(1)
True
>>> bool(range(0))
False
>>> bool(set())
False
>>> bool({5, 6, 2, 5})
True

 

__bool __()

With the special method __bool__(), you can set a "customized" condition that will determine when an object of your class will evaluate to True or False.

According to the Python Documentation:

By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object.

For example, if we have this very simple class:

>>> class Account:
	
	def __init__(self, balance):
		self.balance = balance

You can see that no special methods are defined, so all the objects that you create from this class will always evaluate to True:

>>> account1 = Account(500)
>>> bool(account1)
True
>>> account2 = Account(0)
>>> bool(account2)
True

We can customize this behavior by adding the special method __bool__():

>>> class Account:
	def __init__(self, balance):
		self.balance = balance
		
	def __bool__(self):
		return self.balance > 0

Now, if the account balance is greater than zero, the object will evaluate to True. Otherwise, if the account balance is zero, the object will evaluate to False.

>>> account1 = Account(500)
>>> bool(account1)
True
>>> account2 = Account(0)
>>> bool(account2)
False

💡 Tip: If __bool__() is not defined in the class but the __len__() method is, the value returned by this method will determine if the object is truthy or falsy.

🔹 In Summary

  • Truthy values are values that evaluate to True in a boolean context.
  • Falsy values are values that evaluate to False in a boolean context.
  • Falsy values include empty sequences (lists, tuples, strings, dictionaries, sets), zero in every numeric type, None, and False.
  • Truthy values include non-empty sequences, numbers (except 0 in every numeric type), and basically every value that is not falsy.
  • They can be used to make your code more concise. 

Source: freecodecamp.org