Logical operators in Python combine boolean conditions into compound expressions that control which branch of code your program executes. The three logical operators are and, or, and not. The and operator requires both sides to be true for the whole expression to be true. The or operator requires at least one side to be true. The not operator flips a single boolean value to its opposite. These operators work hand in hand with the comparison operators covered in the previous article on comparison operators in Python, forming the decision-making engine that powers if-statements, while-loops, and every conditional path your program can take. The truthy and falsy rules that govern logical operators build on the boolean concepts introduced in Python boolean data type.
What makes Python logical operators different from those in many other languages is that they do not simply return True or False. They return one of the actual operands, and they stop evaluating as soon as the outcome is determined. This behavior, called short-circuit evaluation, is not just an implementation detail. It is a feature you can use deliberately to write efficient guard conditions and to provide default values with minimal syntax.
The and operator
The and operator evaluates its left operand first. If the left operand is falsy, Python returns that value immediately without evaluating the right operand at all. If the left operand is truthy, Python evaluates and returns the right operand. This means and returns the first falsy value it finds, or the last value if every operand is truthy.
print(True and True) # True
print(True and False) # False
print(3 and 5) # 5 (both truthy, returns last)
print(0 and "hello") # 0 (first is falsy, stops there)The last two examples show that and returns operands, not just booleans. The expression 3 and 5 returns 5 because 3 is truthy, so Python evaluates and returns 5. The expression 0 and "hello" returns 0 because 0 is falsy, so Python stops there and never evaluates the string. This behavior is useful in practice when you want to check a condition and then use a value only if the condition passes.
A common pattern uses and to guard against errors when accessing nested data. If you have a variable that might be None or an empty list, placing it on the left side of and before an indexing operation ensures the indexing only runs when the variable is safe to access. The expression evaluates the left operand first, and only proceeds to the index lookup if the left operand passes the truthiness test.
The or operator
The or operator evaluates its left operand first. If the left operand is truthy, Python returns that value immediately without evaluating the right operand. If the left operand is falsy, Python evaluates and returns the right operand. This means or returns the first truthy value it finds, or the last value if every operand is falsy.
print(True or False) # True
print(False or True) # True
print(0 or "default") # "default" (0 is falsy, use fallback)
print("" or 42) # 42 (empty string is falsy, use fallback)The most practical use of or is providing fallback values. A common pattern checks a variable against several candidates and takes the first one that has a usable value. This replaces a multi-line if-statement with a single expression and appears frequently in Python codebases for setting configuration values and handling optional parameters.
Both and and or can be chained across multiple operands. When you chain multiple and operators, Python evaluates from left to right, stopping at the first falsy value. When you chain multiple or operators, Python evaluates from left to right, stopping at the first truthy value. This chaining works predictably because both operators use short-circuit evaluation, and the later operands are never reached once the result is settled.
The not operator
The not operator is the simplest of the three logical operators. It takes a single operand and returns True if the operand is falsy and False if the operand is truthy. Unlike and and or, the not operator always returns a proper boolean value regardless of the type of its operand. Negating a non-empty string returns False, and negating an empty string returns True.
The not operator is often used to check for empty collections or to negate a condition without writing an else-clause. Writing an if-statement with not in front of a list variable is the idiomatic Python way to check whether the list is empty, and it reads naturally as "if there are no items." Double negation using not twice coerces any value to its boolean equivalent, but using the built-in bool function is clearer for that purpose.
Truthy and falsy values
Every value in Python has an implicit boolean truth value. The values that Python treats as false in a logical context are False, None, the number zero in any numeric type, empty strings, empty sequences like lists and tuples, empty dictionaries, empty sets, and empty ranges. Every other value is treated as true. This includes non-empty strings, non-zero numbers, non-empty collections, and by default all instances of user-defined classes.
This truthiness model is what makes patterns like testing a variable directly in an if-statement work without an explicit length check or comparison to None. An empty string is falsy, so the if-block only executes when the string contains characters. An empty list is falsy, so the if-block only executes when the list has at least one element. Understanding which values are falsy is essential because both and and or use truthiness to decide when to stop evaluating.
Short-circuit evaluation in practice
Short-circuit evaluation is not just a performance optimization. It enables programming patterns that would be awkward or unsafe without it. The guard pattern uses and to prevent accessing attributes or indices on a value that might be None or empty. The condition safely checks an attribute only when the object is not None.
The default value pattern uses or to provide a fallback. A single expression can try a preferred value first, fall back to a secondary value if the preferred one is falsy, and fall back to a hardcoded default if both are falsy. This is a concise way to express a chain of preferences without nesting if-statements.
Short-circuit evaluation also means you should order your conditions from cheapest to most expensive. Put the quick checks on the left and the expensive operations like database queries or file reads on the right. Python will only reach the expensive operations when the cheap checks have already passed, which keeps your programs responsive even when some checks are costly.
Logical operators and control flow
Logical operators reach their full power inside if-statements and while-loops. A condition using and only executes the body when both requirements are satisfied. A condition using or executes the body when at least one requirement is met. These compound conditions are the bridge between the operators you have learned in this section and the control flow structures you will learn next.
Logical operators have lower precedence than comparison operators but higher precedence than assignment. This means the comparison runs first and the logical operator combines the resulting booleans, all without needing extra parentheses. The not operator has higher precedence than and and or, so negating a value before combining it with and works as expected. When the precedence is not obvious from context, add parentheses to make the grouping explicit. They cost nothing and prevent the reader from having to mentally reconstruct the evaluation order.
Rune AI
Key Insights
- Python has three logical operators: and, or, and not.
- The and operator returns the first falsy value or the last truthy value.
- The or operator returns the first truthy value or the last falsy value.
- Short-circuit evaluation stops computation as soon as the result is determined.
- Python treats False, None, zero, and empty collections as falsy; everything else is truthy.
- Logical operators return one of the operands, which makes them useful for setting default values.
Frequently Asked Questions
What does the `and` operator return in Python?
What is short-circuit evaluation?
What values count as false in Python?
Conclusion
Logical operators combine boolean conditions into the compound decisions that give your programs their intelligence. The and keyword requires all conditions to hold, or requires at least one, and not flips a result. Short-circuit evaluation makes these operators both efficient and expressive.
More in this topic
Nested Lists in Python
Learn how to create, access, and modify nested lists in Python. Build grids and matrices, and understand how shallow copies affect multi-dimensional data.
List Comprehensions in Python
Master Python list comprehensions to create, filter, and transform lists in a single line. Learn the syntax, common patterns, and when to use a regular loop instead.
Copy Python Lists
Learn how to copy Python lists using slicing, the copy method, the list constructor, and the copy module. Understand shallow vs deep copies.