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

PythonBoolean Expression

Python Problem Overview


I just learned there are truthy and falsy values in python which are different from the normal True and False.

Can someone please explain in depth what truthy and falsy values are? Where should I use them? What is the difference between truthy and True values and falsy and False values?

Python Solutions


Solution 1 - Python

All values are considered "truthy" except for the following, which are "falsy":

  • None
  • False
  • Zeros, including:
  • Empty sequences and collections, including:
    • [] - an empty list
    • {} - an empty dict
    • () - an empty tuple
    • '' - an empty str
    • b'' - an empty bytes
    • set() - an empty set
    • an empty range, like range(0)
  • objects for which
    • obj.__bool__() returns False
    • obj.__len__() returns 0

A "truthy" value will satisfy the check performed by if or while statements. We use "truthy" and "falsy" to differentiate from the bool values True and False.

Truth Value Testing

Solution 2 - Python

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.

Solution 3 - Python

Python determines the truthiness by applying bool() to the type, which returns True or False which is used in an expression like if or while.

Here is an example for a custom class Vector2dand it's instance returning False when the magnitude (lenght of a vector) is 0, otherwise True.

import math
class Vector2d(object):
	def __init__(self, x, y):
		self.x = float(x)
		self.y = float(y)

	def __abs__(self):
		return math.hypot(self.x, self.y)

	def __bool__(self):
		return bool(abs(self))

a = Vector2d(0,0)
print(bool(a))        #False
b = Vector2d(10,0)    
print(bool(b))        #True

Note: If we wouldn't have defined __bool__ it would always return True, as instances of a user-defined class are considered truthy by default.

Example from the book: "Fluent in Python, clear, concise and effective programming"

Solution 4 - Python

Truthy values refer to the objects used in a boolean context and not so much the boolean value that returns true or false.Take these as an example:

>>> bool([])
False
>>> bool([1])
True
>>> bool('')
False
>>> bool('hello')
True

Solution 5 - Python

Where should you use Truthy or Falsy values ? These are syntactic sugar, so you can always avoid them, but using them can make your code more readable and make you more efficient. Moreover, you will find them in many code examples, whether in python or not, because it is considered good practice.

As mentioned in the other answers, you can use them in if tests and while loops. Here are two other examples in python 3 with default values combined with or, s being a string variable. You will extend to similar situations as well.

Without truthy

if len(s) > 0:
    print(s)
else:
    print('Default value')

with truthy it is more concise:

print(s or 'Default value')

In python 3.8, we can take advantage of the assignment expression :=

without truthy

if len(s) == 0:
    s = 'Default value'
do_something(s)

with truthy it is shorter too

s or (s := 'Default value')
do_something(s)

or even shorter,

do_something(s or (s := 'Default value'))

Without the assignment expression, one can do

s = s or 'Default value'
do_something(s)

but not shorter. Some people find the s =... line unsatisfactory because it corresponds to

if len(s)>0:
    s = s # HERE is an extra useless assignment
else:
    s = "Default value"

nevertheless you can adhere to this coding style if you feel comfortable with it.

Solution 6 - Python

Any object in Python can be tested for its truth value. It can be used in an if or while condition or as operand of the Boolean operations.

The following values are considered False:

  • None
  • False
  • zero of any numeric type, for example, 0, 0L, 0.0, 0j.
  • any empty sequence, for example, '', (), [].
  • any empty mapping, for example, {}.
  • instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False.

All other values are considered True -- thus objects of many types are always true.

Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated.

Solution 7 - Python

In case of if (!id) {}

!expr returns false if its single operand can be converted to true; otherwise, returns true.

If a value can be converted to true, the value is so-called truthy. If a value can be converted to false, the value is so-called falsy.

Examples of expressions that can be converted to false are:

null;

NaN;

0;

empty string ("" or '' or ``);

undefined.

Even though the ! operator can be used with operands that are not Boolean values, it can still be considered a boolean operator since its return value can always be converted to a boolean primitive. To explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double NOT operator or the Boolean constructor.

Example:

n1 = !null               // !t returns true
n2 = !NaN              // !f returns true
n3 = !''                 // !f returns true
n4 = !'Cat'              // !t returns false

While in case of if (id != null) {} it will only check if the value in id is not equal to null

reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT

Solution 8 - Python

Falsy means something empty like empty list,tuple, as any datatype having empty values or None. Truthy means : Except are Truthy

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser6932350View Question on Stackoverflow
Solution 1 - PythonPatrick HaughView Answer on Stackoverflow
Solution 2 - PythonB. EcklesView Answer on Stackoverflow
Solution 3 - Pythonuser1767754View Answer on Stackoverflow
Solution 4 - Pythonadi1yaView Answer on Stackoverflow
Solution 5 - PythonjlaurensView Answer on Stackoverflow
Solution 6 - Pythonuser8170832View Answer on Stackoverflow
Solution 7 - Pythonshotgun02View Answer on Stackoverflow
Solution 8 - PythonVenkateshView Answer on Stackoverflow