Better Programming

Advice for programmers.

Follow publication

Member-only story

How Python Lazily Evaluates Boolean-Based Expressions

A look under the hood of Python

Nathan Patnam
Better Programming
Published in
5 min readJan 27, 2020

--

Lazy evaluation is a concept that many programming languages utilize under the hood to help optimize performance at runtime.

At the heart of it, lazy evaluation means an object is evaluated when it’s needed, not when it’s created. In Python, a neat feature of lazy evaluation is how logical operator-based conditionals are evaluated. For example, let’s say I created a boolean variable, called boolean_result, whose value was the result of the or operator of two functions that both returned booleans.

Creating a variable whose values is the result OR operator of two functions that return booleans

If I were to run this, the output would be the following.

The reason for this is that in order for an or conditional to evaluate to True, the expression on either side of the or has to return True. Since the function condition_one() returns False, then the function condition_two() is executed to check to see what value is returned. As a result, both functions are executed, and the variable boolean_value would have the value of False.

Now let’s see what happens when we change line 8 and make the function condition_one() return True. So if we make the change:

--

--

Nathan Patnam
Nathan Patnam

Written by Nathan Patnam

Software Engineer @ Salesforce & Avid Baker. Happy to chat or mentor, my calendar is at https://calendly.com/nathanpatnam Portfolio: https://nathanpatnam.com

Responses (1)

Write a response