Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python One Line And/Or
1
Python One Line And/Or

How do the Boolean
Code:
and
and
Code:
or
operators work in the context of Python one-liners?

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

Code:
>>> 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
Code:
or
operator applied to non-Boolean values is little known:

Code:
>>> '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:

Code:
>>> 'hello' and 42 42 >>> [] and 42 []

How do the
Code:
and
and
Code:
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

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

Code:
a and b
|
Returns
Code:
b
if the expression
Code:
a
evaluates to
Code:
True
using implicit Boolean conversion. If the expression
Code:
a
evaluates to
Code:
False
, the expression
Code:
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 calledshort-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
Code:
False
. The whole operation must evaluate to
Code:
False
in this case because the logical and only returns
Code:
True
if both operands are
Code:
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:

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

You pass a listinto the if condition. Python then converts the list to a Boolean value to determine which branch to visit next. The empty list evaluates to
Code:
False
. All other lists evaluate to
Code:
True
, so the result is
Code:
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:

https://trinket.io/embed/python/16da0e0846

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

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

[Image: 3D_cover-1024x944.jpg]

Python One-Linerswill 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 tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and 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 Now!!
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: