How do the Boolean `and`

and `or`

operators work in the context of Python one-liners?

You may know the standard use of the logical operators applied to Boolean values:

>>> True and False False >>> False or True True

But there’s more to these operators that only experts in the art of writing concise Python one-liners know.

For instance, the following use of the `or`

operator applied to non-Boolean values is little known:

>>> 'hello' or 42 'hello' >>> [] or 42 42

Similarly, the following use of the and operator often causes confusion in readers of advanced Python one-liners:

>>> 'hello' and 42 42 >>> [] and 42 []

How do the `and`

and `or`

operator work when applied to non-Boolean operands?

To understand what is going on, you need to look at the definitions of the Boolean operators:

Operator | Description |
---|---|

`a or b` | Returns `b` if the expression `a` evaluates to `False` using implicit Boolean conversion. If the expression `a` evaluates to `True` , the expression `a` is returned. |

`a and b` | Returns `b` if the expression `a` evaluates to `True` using implicit Boolean conversion. If the expression `a` evaluates to `False` , the expression `a` is returned. |

Study these explanations thoroughly! The return value is of the same data type of the operands—they only return a Boolean value if the operands are already Boolean!

This optimization is called short-circuiting and it’s common practice in many programming languages. For example, it’s not necessary to evaluate the result of the second operand of an and operation if the first operand evaluates to `False`

. The whole operation must evaluate to `False`

in this case because the logical and only returns `True`

if both operands are `True`

.

Python goes one step further using the property of implicit Boolean conversion. Every object can be implicitly converted to a Boolean value. That’s why you see code like this:

l = [] if l: print('hi') else: print('bye') # bye

You pass a list into the if condition. Python then converts the list to a Boolean value to determine which branch to visit next. The empty list evaluates to `False`

. All other lists evaluate to `True`

, so the result is `bye`

.

Together, short circuiting and implicit Boolean conversion allow the logical operators and and or to be applied to any two Python objects as operands. The return value always is one of the two operands using the short circuiting rules described in the table.

Try it yourself in our interactive code shell:

**Exercise**: Guess the output! Then check if you were right! Create your own crazy operands and evaluate them by executing the code in your browser.

## Python One-Liners Book: Master the Single Line First!

**Python programmers will improve their computer science skills with these useful one-liners.**

*Python One-Liners* will teach you how to read and write “one-liners”: ** concise statements of useful functionality packed into a single line of code. **You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce ** key computer science concepts **and

**. You’ll learn about advanced Python features such as**

*boost your coding and analytical skills**,*

**list comprehension****,**

*slicing***,**

*lambda functions***,**

*regular expressions***and**

*map***functions, and**

*reduce***.**

*slice assignments*You’ll also learn how to:

- Leverage data structures to
**solve real-world problems**, like using Boolean indexing to find cities with above-average pollution - Use
**NumPy basics**such as*array*,*shape*,*axis*,*type*,*broadcasting*,*advanced indexing*,*slicing*,*sorting*,*searching*,*aggregating*, and*statistics* - Calculate basic
**statistics**of multidimensional data arrays and the K-Means algorithms for unsupervised learning - Create more
**advanced regular expressions**using*grouping*and*named groups*,*negative lookaheads*,*escaped characters*,*whitespaces, character sets*(and*negative characters sets*), and*greedy/nongreedy operators* - Understand a wide range of
**computer science topics**, including*anagrams*,*palindromes*,*supersets*,*permutations*,*factorials*,*prime numbers*,*Fibonacci*numbers,*obfuscation*,*searching*, and*algorithmic sorting*

By the end of the book, you’ll know how to ** write Python at its most refined**, and create concise, beautiful pieces of “Python art” in merely a single line.

*Get your Python One-Liners on Amazon!!*

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.