Definition of the or operator in Python
The or operator is a boolean logical operator in Python that allows you to combine two conditional expressions. It returns True if at least one of the two expressions is true. It is one of the three fundamental logical operators in the language, alongside and and not.
If you want to master Python in depth, including its logical operators and all its subtleties, our complete Python course will guide you step by step through your learning journey.
The basic syntax is as follows:
expression1 or expression2Python first evaluates expression1. If it is considered true (truthy), it immediately returns its value without even evaluating expression2. If expression1 is false (falsy), Python evaluates and returns the value of expression2. This mechanism is called short-circuit evaluation.
Here is the truth table for the or operator:
| Expression A | Expression B | A or B |
|---|---|---|
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
In Python, the or operator does not necessarily return True or False. It returns the actual value of one of the two operands, which distinguishes it from many other programming languages.
Understanding truthy and falsy values
To use or properly, it is essential to understand what Python considers true (truthy) or false (falsy). In Python, the following values are considered falsy:
FalseNone0(integer zero)0.0(float zero)""(empty string)[](empty list)()(empty tuple){}(empty dict)set()(empty set)
All other values are considered truthy. This means that the or operator works well beyond simple booleans:
# With booleans
print(True or False) # True
print(False or True) # True
print(False or False) # False
# With other types
print(0 or 42) # 42
print("" or "Hello") # Hello
print(None or "value") # value
print([] or [1, 2, 3]) # [1, 2, 3]As you can see, the or operator returns the first truthy value encountered, or the last value if all are falsy:
# Returns the first truthy value
print(0 or "" or None or "Python") # Python
print("First" or "Second") # First
# All values are falsy: returns the last one
print(0 or "" or None or []) # []
print(False or 0) # 0Practical examples of the or operator
Usage in if conditions
The most common use of or is found in conditional structures, where you want to check if at least one condition is met:
age = 15
is_accompanied = True
if age >= 18 or is_accompanied:
print("Access granted")
else:
print("Access denied")
# Result: Access granted (because is_accompanied is True)You can combine multiple conditions with or:
day = "saturday"
if day == "saturday" or day == "sunday" or day == "wednesday":
print("Possible rest day")
else:
print("Work day")Be careful: each condition must be complete. Writing day == "saturday" or "sunday" does not work as you might expect, because "sunday" alone is always truthy. Use the in operator instead for this type of check: day in ("saturday", "sunday", "wednesday").
Default values with or
A very common and elegant use of or in Python is to define default values:
def greet(name=None):
name = name or "Visitor"
print(f"Hello, {name}!")
greet("Alice") # Hello, Alice!
greet("") # Hello, Visitor!
greet(None) # Hello, Visitor!
greet() # Hello, Visitor!This pattern is extremely practical for def parameters that can be None or empty. However, be careful: if 0 or False are legitimate values, this pattern will replace them too:
def configure_port(port=None):
# Warning: port = 0 would be replaced by 8080!
port = port or 8080
print(f"Listening on port {port}")
configure_port(3000) # Listening on port 3000
configure_port(0) # Listening on port 8080 (potential problem!)
configure_port(None) # Listening on port 8080To avoid this pitfall, prefer the ternary operator or an explicit test with is None when 0, False or an empty string are valid values: port = port if port is not None else 8080.
Chaining or to select the first available value
You can chain multiple or operators to select the first non-empty value from several sources:
import os
# Search for configuration from multiple sources
username = (
os.environ.get("USER_NAME")
or os.environ.get("USERNAME")
or os.environ.get("LOGNAME")
or "unknown_user"
)
print(f"User: {username}")This pattern is particularly useful in configuration management where you want to check multiple data sources before using a default value.
Combination with and and not
The or operator can be combined with other logical operators to create complex conditions. It is important to know the order of precedence:
| Priority | Operator | Description |
|---|---|---|
| 1 (high) | not | Logical negation |
| 2 | and | Logical AND |
| 3 (low) | or | Logical OR |
This means that and is evaluated before or:
# Without parentheses
result = True or False and False
print(result) # True
# Equivalent to: True or (False and False) → True or False → True
# With parentheses to change the order
result = (True or False) and False
print(result) # False
# (True or False) → True, then True and False → FalseTo avoid any ambiguity and improve the readability of your code, we recommend using explicit parentheses when combining and and or in the same expression.
Here is a concrete example combining all three operators:
is_admin = False
is_moderator = True
is_banned = False
if (is_admin or is_moderator) and not is_banned:
print("Access to moderation panel")
else:
print("Access denied")
# Result: Access to moderation panelShort-circuit evaluation in detail
The short-circuit evaluation of or can have important implications, especially when expressions have side effects:
def check_database():
print("Checking database...")
return True
def check_cache():
print("Checking cache...")
return True
# If cache returns True, the database is never queried
result = check_cache() or check_database()
# Only prints: Checking cache...This behavior is useful for optimizing performance. You can place the least expensive checks first:
def is_in_cache(key):
"""Fast in-memory check"""
return cache.get(key)
def is_in_database(key):
"""Slow database query"""
return db.query(key)
# The database is only consulted if the cache doesn't contain the key
result = is_in_cache("user_123") or is_in_database("user_123")Short-circuit evaluation is also useful for avoiding errors:
data = None
# Without short-circuit evaluation, data.get() would cause an error
value = data or {}
result = value.get("key", "default")
print(result) # defaultUsage with comprehensions and functions
The or operator integrates naturally into list comprehensions and with functions like lambda:
# Filter with or in a list comprehension
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered = [n for n in numbers if n < 3 or n > 8]
print(filtered) # [1, 2, 9, 10]
# With a lambda function
validate = lambda x: x or "Not specified"
print(validate("Alice")) # Alice
print(validate("")) # Not specified
print(validate(None)) # Not specifiedYou can also use or in the print function to display default values:
name = ""
print(name or "Anonymous") # Anonymous
result = None
print(f"Result: {result or 'No result'}") # Result: No resultUsage with any() for collections
When you need to check if at least one element of a collection satisfies a condition, the built-in any() function is the equivalent of multiple chained or operators:
grades = [12, 8, 15, 6, 18]
# With or (impractical for a list)
has_good_grade = grades[0] >= 16 or grades[1] >= 16 or grades[2] >= 16
# With any() (elegant and flexible)
has_good_grade = any(grade >= 16 for grade in grades)
print(has_good_grade) # True (thanks to 18)
# any() also uses short-circuit evaluation
# It stops as soon as a True value is foundThe any() function is particularly recommended when you have a variable number of conditions to check with a logical OR. It is more readable and more performant than chaining or operators.
Best practices
Here are the essential recommendations for using or effectively in Python:
- Use parentheses when combining
orwithandto make the intent explicit. - Prefer
inrather than multipleoroperators to test membership:x in ("a", "b", "c")rather thanx == "a" or x == "b" or x == "c". - Place the least expensive conditions first to take advantage of short-circuit evaluation.
- Be careful with default values:
x or default_valuealso replaces0,Falseand"". Usex if x is not None else default_valueif necessary. - Use
any()when you have a variable number of logical OR conditions to check. - Avoid overly long expressions: if a condition with
orexceeds 3-4 terms, consider breaking it into intermediate variables to improve readability.
# ❌ Hard to read
if user.age >= 18 or user.has_permission or user.is_admin or user.is_moderator or user.parent_approved:
grant_access()
# ✅ More readable with intermediate variables
is_adult = user.age >= 18
has_rights = user.has_permission or user.is_admin or user.is_moderator
has_parent_approval = user.parent_approved
if is_adult or has_rights or has_parent_approval:
grant_access()
# ✅ Even more readable with any()
conditions = [
user.age >= 18,
user.has_permission,
user.is_admin,
user.is_moderator,
user.parent_approved,
]
if any(conditions):
grant_access()Frequently asked questions
What is the difference between or and | in Python?
The or operator is a logical operator that works with short-circuit evaluation and returns one of the two operand values. The | operator is a bitwise operator that performs a bitwise OR on integers. Since Python 3.9, | can also be used to merge dict. As a general rule, use or for logical conditions and | for bit operations or dictionary merging.
Why doesn't or always return True or False?
This is a design choice in Python that favors practicality. By returning the actual value of the operand (rather than its boolean equivalent), or enables elegant patterns such as default values (name or "Anonymous"). If you need a strict boolean, you can wrap the expression with bool(): bool(expression1 or expression2).
Can you use or in a lambda expression?
Yes, absolutely. The or operator can be used in any Python expression, including lambda. For example: clean = lambda x: x.strip() or "empty". This is a concise way to create functions that return default values.
How can I learn to master logical operators in Python?
The best way to master or and other logical operators is to practice with real projects. We recommend following our complete Python course on Believemy, which covers logical operators, conditional structures and all the subtleties of the language in detail through practical exercises and real-world projects.