08-23-2020, 07:22 AM
Python One Line And/Or
How do the Boolean and operators work in the context of Python one-liners?
You may know the standard use of the logical operators applied to Boolean values:
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 operator applied to non-Boolean values is little known:
Similarly, the following use of the and operator often causes confusion in readers of advanced Python one-liners:
How do the and 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
|
Returns if the expression evaluates to using implicit Boolean conversion. If the expression evaluates to , the expression is returned.
|
Returns if the expression evaluates to using implicit Boolean conversion. If the expression evaluates to , the expression 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. The whole operation must evaluate to in this case because the logical and only returns if both operands are .
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:
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. All other lists evaluate to , so the result is .
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]](https://blog.finxter.com/wp-content/uploads/2020/06/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!!
How do the Boolean
Code:
andCode:
orYou may know the standard use of the logical operators applied to Boolean values:
Code:
>>> True and False
False
>>> False or True
TrueBut 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:
orCode:
>>> 'hello' or 42 'hello'
>>> [] or 42
42Similarly, 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:
andCode:
orTo understand what is going on, you need to look at the definitions of the Boolean operators:
Operator |
Description
Code:
a or bReturns
Code:
bCode:
aCode:
FalseCode:
aCode:
TrueCode:
aCode:
a and bReturns
Code:
bCode:
aCode:
TrueCode:
aCode:
FalseCode:
aStudy 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:
FalseCode:
FalseCode:
TrueCode:
TruePython 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')
# byeYou 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:
FalseCode:
TrueCode:
byeTogether, 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]](https://blog.finxter.com/wp-content/uploads/2020/06/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!!

