The or
operator in Python allows you to check if at least one of multiple conditions is True. It returns True if any of the conditions evaluates to True. The or
operator is also called the logical OR operator. Understanding how to use or
correctly can help write more robust and Pythonic code.
In this comprehensive guide, we will cover the following topics related to the or
operator:
Table of Contents
Open Table of Contents
Definition and Syntax of the or
Operator
The or
keyword in Python represents the Boolean logical OR operator. The syntax for or
is:
expr1 or expr2
Where expr1
and expr2
are two boolean expressions that will be evaluated from left to right.
The or
operator returns True
if either the left side expression expr1
or the right side expression expr2
evaluates to True
. It will return False
only when both expressions evaluate to False
.
Here is the truth table for the or
operator:
expr1 | expr2 | expr1 or expr2 |
---|---|---|
True | True | True |
True | False | True |
False | True | True |
False | False | False |
As the truth table shows, the or
expression only evaluates to False
when both expr1
AND expr2
are False. As long as at least one expression is True, the overall or
expression will be True.
Truth Value Testing
In Python, the or
operator actually returns one of the operand values, not just a Boolean value. It will return the first truthy operand it encounters when evaluating left to right, or the last falsy operand if both are falsy.
Any object in Python has an inherent Boolean truth value, even if it is not an explicit Boolean True or False. The truth testing rules are:
- Numeric zero (0), None, empty strings, sequences or collections evaluate to False
- Non-zero numbers, non-empty strings, sequences or collections evaluate to True
So the or
operator will return the first truthy operand:
print(0 or 10) # 10
print([] or 'hello') # 'hello'
print(True or 100) # True
And it will return the last falsy operand if both are falsy:
print(0 or False) # False
print(None or '') # ''
This allows you to use or
as a way to choose between values.
Short-Circuit Evaluation
The or
operator exhibits short-circuiting behavior - it will stop evaluation as soon as it encounters the first truthy value and will not evaluate the rest of the conditions.
This is important for efficiency as well as avoiding errors:
# Efficiency - avoids evaluating second expression
print(True or slow_function())
# Avoid errors - second expression not evaluated
print(False or 1/0)
Short-circuit evaluation avoids unnecessary work and avoids evaluating expressions that might cause errors.
Differences Between or
and and
While or
returns True if either one or both expressions are truthy, the and
operator behaves differently:
- The
and
operator returns True only if both left and right side expressions evaluate to True. - It short-circuits and returns the first falsy value it encounters if any.
So and
is useful for ensuring all given conditions are met, while or
checks if any one condition is met.
Here is a comparison of and
vs or
outputs:
print(True and True) # True
print(True and False) # False
print(False and True) # False
print(False and False) # False
print(True or True) # True
print(True or False) # True
print(False or True) # True
print(False or False) # False
Common Use Cases
Some common use cases taking advantage of or
short-circuiting behavior are:
Condition Checking
Checking if at least one condition from a set of conditions is True:
if x > 0 or y > 0 or z > 0:
print("At least one value is positive")
Only one condition needs to be True to print the message. The remaining conditions will not be evaluated after the first truthy one.
Default Values
Substituting default values if the original value does not exist:
user_name = username or 'Anonymous'
This will set user_name
to the actual username if it exists, else default to ‘Anonymous’.
Coalescing Values
Coalescing chained or
expressions to return first truthy value:
first_non_null = var1 or var2 or var3 or 'default'
This is useful for returning the first non-null variable from a chain, else defaulting to a set value.
Common Pitfalls and Best Practices
Here are some common pitfalls and best practices to keep in mind when using the or
operator:
-
Avoid double negatives like
not a or not b
. This can be confusing and error-prone. -
When mixing
and
andor
in complex expressions, use parentheses for clarity and avoiding errors. -
Make sure each part of an
or
expression contains valid object types that evaluate properly to True/False values. -
Be careful using
or
chains with mutable objects like lists or dictionaries. This can cause unexpected side effects. -
Keep
or
expressions simple and readable. Compact code likevar1 or var2 or var3
is prone to mistakes. -
Favor explicit comparisons over implicit type conversions in
or
expressions for readability.
Performance Considerations
Since or
short-circuits, it can provide a performance boost for expensive expressions or function calls:
# Slow network call avoided
if cached_value or make_network_call():
process(value)
However, premature optimization should be avoided, especially in simple cases where readability is more important than marginal performance gains from short-circuiting.
Alternatives to or
-
An
if/else
statement may be easier to read for complex conditionals. -
Set a default value using the Walrus operator:
user_name := username or 'Anonymous'
-
The built-in
functools.reduce
function can be used to emulate anor
chain. -
List comprehensions are useful for condition checking on collections.
So consider if an explicit conditional or other Python feature may better suit your use case.
Examples and Exercises
Study the following examples and complete the exercises to check your understanding of or
:
Example 1 - Return first truthy value:
print(0 or 100 or 200) # 100
vals = [0, 10, 20]
print(vals[0] or vals[1] or vals[2]) # 10
Example 2 - Default values:
user_color = favorite_color or 'blue'
user_name = provided_name or 'Anonymous'
Example 3 - Code readability:
# Hard to read
if d or e or f:
print('complex!')
# Clearer
if d or e or f:
print('complex!')
Exercises
-
Print the first positive number from the list
[0, -1, 5, -3]
usingor
. -
Set the variable
message
to “‘Empty’” iftext
is empty else set it totext
. -
Fix the code snippet to avoid a divide by zero error:
x = False or 1/0
Solutions:
print([0, -1, 5, -3][0] or [0, -1, 5, -3][2])
# 5
message = text or "'Empty'"
x = False or 1
Proper use of the or
operator allows writing conditional code that is robust, efficient, and Pythonic. With thepower of short-circuit evaluation, it serves as a useful tool for condition checking, default values, and more. Follow best practices of readability, avoiding complexity, and explicit checks over implicit type conversions.
Conclusion
The or
operator in Python provides a shorthand for ensuring at least one condition evaluates to True. Its short-circuiting behavior improves efficiency and avoids errors. Common use cases include condition checking, default values, and coalescing. Appropriate use of or
can improve code clarity and reduce complexity versus lengthy if/else blocks. A deep understanding of or
will enable writing more idiomatic and Pythonic code.