What is Short Circuit Evaluation in Python?

Short circuit evaluation in any programming language — e.g., Python — is the act of avoiding executing parts of a Boolean expression that have no effect on the final result. For example, if you already know that A is False, you can conclude that A and XXX is False no matter what the result of subexpression XXX is.

Short Circuit Logical AND

Say, you want to calculate the result of the logical AND expression A and B but you already know that A=False.

Because of your knowledge of the first part of the expression, you already know the result of the overall expression evaluates to False no matter what the second part B evaluates to.

So the programming language skips computation of the remaining expression B and just returns the result False.

Here’s an example for the Python programming language that shows that the second part of the logical expression, i.e., the print function print('hello world'), is not evaluated:

>>> False and print('hello world')
False

Note: Python allows any object to be used as a Boolean expression because any object implements the implicit bool() conversion to a Boolean type.

You can see that if the first part is False, Python does not even bothering executing the second part.

If you had instead chosen a first part that evaluates to True, Python executes the second part of the expression which can be seen here:

>>> True and print('hello world')
hello world

In fact, Python simply returns the second part without modification if the first part evaluates to True.

Short Circuit Logical OR

Another example is the logical OR expression A or B and you already know that A=True.

Now, you can simply skip all remaining computations and return True right away which is the result of the overall computation.

Here’s an interesting example:

a = 1 > 0

if a or (1 / 0 == 0):
    print('ok')
else:
    print('nok')

# Result is 'ok'

The right-hand side of the expression (1 / 0 == 0) is not executed. Due to the short-circuiting, Python does not raise an error message '... cannot divide by zero ...'.

If you had switched the logical operands it seems semantically identical. But due to short-circuiting, this leads to an error message!

a = 1 > 0

if (1 / 0 == 0) or a:
    print('ok')
else:
    print('nok')

Output:

Traceback (most recent call last):
  File "C:\Users\...\code.py", line 3, in <module>
    if (1 / 0 == 0) or a:
ZeroDivisionError: division by zero

So, short-circuiting really matters for programming languages such as Python!

Where To Go From Here?

Python is full of those small optimizations. Every master coder knows them? Want to learn them, step-by-step, day-by-day?

Join my free Python email course for continuous improvement! It’s fun!

[Free Cheat Sheets] “Coffee Break Python” Email Course with Python Cheat Sheets!