The difference is short-circuit evaluation, a subtle yet sometimes very significant difference.
In short-circuit evaluation, the computer executes the minimum code to figure out the value of a boolean expression.
If x is true in an “x or y” expression, then the expression is true no matter what y is. (true or true = true, also true or false = true)
A similar thing happens in “x and y”. Here, if x is false, the expression is false no matter what y is.
The short-circuit ignores y in either one of these cases:
1. x is true in an “x or y” expression
2. x is false in an “x and y” expression
The flip side of short-circuit is eager evaluation.
With eager evaluation, both x and y are evaluated no matter what.
Eager evaluation might be useful when x and y are functions that have side effects, i.e. they also do something rather than just return a value. The functions might for example, try to write to a database and return true/false based on whether the operation is successful or not.
In Python, the ‘and’ and ‘or’ operators perform short-circuit evaluation, while ‘&’ and ‘|’ do eager evaluation.
Here is some example code. These functions return a boolean value, as well as do something by printing a statement.
def foo(x): print("Foo here!") return x def bar(x): print("Bar here!") return x
This is what happens with lazy evaluation:
foo(False) and bar(True)
Foo here!
foo(True) or bar(False)
Foo here!
In both cases, only the foo
function runs, because the value of the expression is known without having to execute bar
.
This is what happens with eager evaluation:
foo(False) & bar(True)
Foo here! Bar here!
foo(False) & bar(True)
Foo here! Bar here!
Now, with the eager evaluation operators, both functions run despite having foo
determine the value of the boolean expression on its own.