201

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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 36
    If `bool(value)` results in `True`, then `value` is *truthy*. – wnnmaw Oct 11 '16 at 18:02
  • 5
    You invented those words yourself, didn't you? Anyway, see [`__nonzero__`](https://docs.python.org/2/reference/datamodel.html#object.__nonzero__) and [`__bool__`](https://docs.python.org/3.1/reference/datamodel.html#object.__bool__) – zvone Oct 11 '16 at 18:03
  • 7
    Truthy/Falsy values are just conveniences for situations where you need a binary test of some kind. It allows for simpler code, and simpler code is often easier to read with less chance for bugs. – Mark Ransom Oct 11 '16 at 18:04
  • 2
    P.S. `True` and `False` are specializations of the `int` type with values of `1` and `0`. – Mark Ransom Oct 11 '16 at 18:05
  • 4
    @zvone Truthy and falsy is used commonly in code golf, if programming languages do not have boolean values. – MilkyWay90 Nov 11 '18 at 22:35
  • 11
    @zvone: 'Truthy' and 'falsy' are widely used when comparing programming languages, e.g. PHP vs PERL vs Python vs JS. (Absolutely not just code golf). – smci Jul 29 '19 at 07:44
  • Related: https://stackoverflow.com/questions/47007680 – Karl Knechtel Jul 08 '22 at 08:44

8 Answers8

312

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:
  • 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
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
  • 14
    Great list, thanks. Entirely academic question, but do you know what the execution order is? Was thinking that you could create an object where __bool__ returns True and __len__ returns 0 (or vice versa). – Hayden Crocker Oct 30 '17 at 10:44
  • 32
    @HaydenCrocker It looks for `__bool__` first, then `__len__`. If neither is defined, all instances are considered "true". This is discussed in the docs for the [`object.__bool__`](https://docs.python.org/3/reference/datamodel.html#object.__bool__) method – Patrick Haugh Oct 30 '17 at 16:36
  • 8
    In Python versions prior to 3.5, [time objects](https://docs.python.org/3/library/datetime.html#time-objects) representing midnight UTC were considered False. [This article](https://lwn.net/Articles/590299/) gives an overview of a bug report of the issue and the eventual resolution. – Jason V. Sep 20 '18 at 20:15
  • 2
    Interestingly for the datetime package, datetime.min is truthy while timedelta(0) is falsy. – David Kinghorn Apr 18 '19 at 15:26
  • 8
    @DavidKinghorn That makes sense though, right? The minimum datetime value is just a date like any other, it's not like zero in any way. By contrast, `timedelta(0)` is like zero. This got brought up when it was discovered that time values representing midnight were falsy, which was eventually fixed: https://lwn.net/Articles/590299/ – Patrick Haugh Apr 18 '19 at 15:56
  • 4
    `bytearray()`, `frozenset()`, `memoryview(b'')`, `{}.keys()`, `{}.items()`, `{}.values()` – wim Aug 05 '19 at 02:55
  • 1
    Be careful here. There are some very popular constructs from outside the standard library that don't apply: `print("truthy") if np.array(0) else "falsy"` – user1717828 Sep 21 '19 at 11:47
  • 1
    The bit about `__bool__` and `__len__` needs to be rewritten to be technically accurate; `__len__` will not be considered at all if `__bool__` is explicitly defined. I couldn't come up with good wording, however. – Karl Knechtel Jul 08 '22 at 08:54
  • @Karl Why did you write "**like** `bytearray(b'')`" and "`memoryview(b'')`"? Aren't those the *only* ways to write an empty `bytearray` and `memoryview`? For `range`, on the other hand, there's more than one empty range, like `range(1, 1)`. – wjandrea Aug 09 '22 at 18:12
  • Is it worth clarifying that `False` is technically a number? – wjandrea Aug 09 '22 at 18:16
  • @user1717828 What's weird about `np.array(0)`? It behaves like a scalar `0`, which is as expected, no? Maybe you mean something like `np.array([0, 0])`, which raises a `ValueError`, or `np.array([])`, which is falsy, but deprecated. – wjandrea Aug 09 '22 at 18:34
  • 1
    @wjandrea there are other (less obvious) calls, e.g `bytearray([])` or `bytearray('', 'utf-8')` (or any valid encoding). But there is only one way for the *value* to be empty. I had thought to clarify it because these ones involve a function call rather than a literal syntax. However, I agree now that they should just look like the other examples, so I'll edit. – Karl Knechtel Aug 09 '22 at 19:34
  • Re booleans being a subtype of integer, I don't think that's on topic here, and there should be another canonical covering it. – Karl Knechtel Aug 09 '22 at 19:38
  • @KarlKnechtel `As explained in the documentation, all values are considered "truthy" except for the following, which are "falsy":` - No, neither that linked part of the documentation nor any other part of the documentation explains "truthy"/"falsy". It explains true/false. I think a prominent answer specifically about terminology should really get it right... – Kelly Bundy Aug 09 '22 at 20:21
  • Both the community and the documentation are being colloquial, and "truthy" and "falsy" aren't real terminology. Saying that an object is "considered true", as the documentation puts it, also isn't very precise; the context of an `if` statement, or an `and` or `or` operator, or explicit conversion to `bool`, is required. – Karl Knechtel Aug 09 '22 at 23:27
  • Could be corrected to be valid for Python 2.x if mentioning `__nonzero__` (the `__bool__` method is Python 3.x) – Jason S Nov 30 '22 at 20:43
102

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.

Georgy
  • 12,464
  • 7
  • 65
  • 73
B. Eckles
  • 1,626
  • 2
  • 15
  • 27
  • 1
    I suggest trying these things out in a Python shell and seeing for yourself. ;) `if my_list` means "if my_list is not empty", and `if not my_list` means "if my_list is empty". – B. Eckles Oct 11 '16 at 18:22
  • 1
    ok i have last little confusion , i have seen many places like `if a:` what this type of conditions means ? is it mean if a is true or means if a is false ? or it means if a is truthy or if a is falsy ? –  Oct 11 '16 at 18:24
  • 1
    It means "if a is true". As I described in my answer, and as others have described in comments and other answers, different things are CONSIDERED True or False, but are not actually so. An empty list, for example, is considered False. That's why `if []:` would never execute. – B. Eckles Oct 11 '16 at 18:26
  • means if a: means if a is true (when a is integer or string ) and if a: means false if a is empty list or empty dict or false values ! –  Oct 11 '16 at 18:28
  • Yes, assuming I understand you properly. ^_^ – B. Eckles Oct 11 '16 at 18:29
8

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"

user1767754
  • 23,311
  • 18
  • 141
  • 164
6

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
adi1ya
  • 404
  • 1
  • 7
  • 10
4

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.

jlaurens
  • 529
  • 5
  • 10
4

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.

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
user8170832
  • 51
  • 1
  • 4
0

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

shotgun02
  • 756
  • 4
  • 14
-3

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