Short-Circuiting the Evaluation
00:00 In this lesson, you’ll see how Python makes use of something called short-circuit evaluation to sometimes speed up program execution. Short-circuit evaluation, sometimes called lazy evaluation, takes advantage of something you learned in a previous lesson.
Remember that sometimes you never even have to evaluate the second operand of an
and operation. And Python knows that too. If the first expression is false, the result of the entire operation is
To demonstrate short-circuit evaluation, we’ll use these two functions. Each returns a
True or a
False value but prints a statement before that, so you’ll see when each function is executed. And I have those two functions in this Python file called
both functions had to be evaluated because Python couldn’t tell from just the first expression what the overall result was going to be. Again, as the first expression evaluates to
True, the second expression must be evaluated to determine the result of the
and operation. Notice also the result in those cases is actually what the righthand operand evaluated to.
03:05 How might you as a programmer take advantage of short-circuit evaluation? Here are a couple of suggestions. If one of your two expressions takes much longer to evaluate than the other, take that expression and put it last.
There’s a possibility it won’t be executed at all. Sometimes another idea is to put an expression that you know will most likely be false first. So when it does evaluate to
False, there’s no need to evaluate the second.
Become a Member to join the conversation.