0
0
Pythonprogramming~5 mins

Truthy and falsy values in Python

Choose your learning style9 modes available
Introduction
Python uses truthy and falsy values to decide if something is true or false in conditions, making decisions easy and natural.
Checking if a list has any items before processing it.
Deciding if a string is empty or has content.
Testing if a number is zero or not before calculations.
Controlling flow in if statements without writing explicit comparisons.
Simplifying code by relying on Python's built-in truthiness rules.
Syntax
Python
if value:
    # runs if value is truthy
else:
    # runs if value is falsy
In Python, values like 0, None, empty collections ([], {}, '', ()), and False are falsy.
All other values are considered truthy.
Examples
Zero is falsy, so the else block runs.
Python
if 0:
    print("This won't print")
else:
    print("Zero is falsy")
Non-empty strings are truthy, so this prints.
Python
if "hello":
    print("Non-empty string is truthy")
Empty lists are falsy, so else block runs.
Python
if []:
    print("This won't print")
else:
    print("Empty list is falsy")
None is falsy, so else block runs.
Python
if None:
    print("This won't print")
else:
    print("None is falsy")
Sample Program
This program checks each value in the list and prints if it is truthy or falsy.
Python
values = [0, 1, "", "text", [], [1,2], None, True, False]

for v in values:
    if v:
        print(f"{repr(v)} is truthy")
    else:
        print(f"{repr(v)} is falsy")
OutputSuccess
Important Notes
Remember that empty containers like lists, tuples, sets, and dictionaries are falsy.
Custom objects are truthy by default unless they define __bool__ or __len__ methods.
Using truthy/falsy values can make your code shorter and easier to read.
Summary
Python treats certain values as true or false automatically in conditions.
Falsy values include 0, None, False, and empty containers like '', [], (), and {}.
All other values are truthy and make conditions run the 'if' block.