Create an account


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

#1
Python One Line And/Or

<div><p>How do the Boolean <code>and</code> and <code>or</code> operators work in the context of Python one-liners?</p>
<p>You may know the standard use of the logical operators applied to Boolean values:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> True and False
False
>>> False or True
True</pre>
<p>But there’s more to these operators that only experts in the art of writing concise <a href="https://blog.finxter.com/python-one-line-x/" title="Python One Line X" target="_blank" rel="noreferrer noopener">Python one-liners</a> know. </p>
<p>For instance, the following use of the <code>or</code> operator applied to non-Boolean values is little known:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> 'hello' or 42 'hello'
>>> [] or 42
42</pre>
<p>Similarly, the following use of the and operator often causes confusion in readers of advanced Python one-liners:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> 'hello' and 42
42
>>> [] and 42
[]</pre>
<p>How do the <code>and</code> and <code>or</code> operator work when applied to non-Boolean operands?</p>
<p>To understand what is going on, you need to look at the definitions of the Boolean operators:</p>
<figure class="wp-block-table is-style-stripes">
<table>
<thead>
<tr>
<th>Operator</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>a or b</code></td>
<td>Returns <code>b</code> if the expression <code>a</code> evaluates to <code>False</code> using implicit Boolean conversion. If the expression <code>a</code> evaluates to <code>True</code>, the expression <code>a</code> is returned.</td>
</tr>
<tr>
<td><code>a and b</code></td>
<td>Returns <code>b</code> if the expression <code>a</code> evaluates to <code>True</code> using implicit Boolean conversion. If the expression <code>a</code> evaluates to <code>False</code>, the expression <code>a</code> is returned.</td>
</tr>
</tbody>
</table>
</figure>
<p>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!</p>
<p>This optimization is called<a href="https://blog.finxter.com/python-one-line-if-without-else/" title="Python One Line If Without Else" target="_blank" rel="noreferrer noopener"> short-circuiting</a> 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</code>. The whole operation must evaluate to <code>False</code> in this case because the logical and only returns <code>True</code> if both operands are <code>True</code>. </p>
<p>Python goes one step further using the property of <a href="https://blog.finxter.com/how-to-apply-a-logical-operator-to-all-elements-in-a-python-list/" target="_blank" rel="noreferrer noopener" title="{AND, OR, NOT} How to Apply Logical Operators to All List Elements in Python?">implicit Boolean conversion.</a> Every object can be implicitly converted to a Boolean value. That’s why you see code like this:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">l = []
if l: print('hi')
else: print('bye')
# bye</pre>
<p>You pass a <a href="https://blog.finxter.com/python-lists/" title="The Ultimate Guide to Python Lists" target="_blank" rel="noreferrer noopener">list </a>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 <code>False</code>. All other lists evaluate to <code>True</code>, so the result is <code>bye</code>. </p>
<p>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. </p>
<p>Try it yourself in our interactive code shell:</p>
<p> <iframe src="https://trinket.io/embed/python/16da0e0846" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p><strong>Exercise</strong>: Guess the output! Then check if you were right! Create your own crazy operands and evaluate them by executing the code in your browser. </p>
<h2>Python One-Liners Book</h2>
<p><strong>Python programmers will improve their computer science skills with these useful one-liners.</strong></p>
<figure class="wp-block-image size-medium is-resized"><a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noopener noreferrer"><img src="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-1024x944.jpg" alt="Python One-Liners" class="wp-image-10007" width="512" height="472" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x277.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x708.jpg 768w" sizes="(max-width: 512px) 100vw, 512px" /></a></figure>
<p><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE"><em>Python One-Liners</em> </a>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.</p>
<p>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:</p>
<p><strong>•</strong>&nbsp;&nbsp;Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution<br /><strong>•</strong>&nbsp;&nbsp;Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics<br /><strong>•</strong>&nbsp;&nbsp;Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning<br /><strong>•</strong>&nbsp;&nbsp;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<br /><strong>•</strong>&nbsp;&nbsp;Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting</p>
<p>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.</p>
<p><strong><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE"><em>Get your Python One-Liners Now!!</em></a></strong></p>
</div>


https://www.sickgaming.net/blog/2020/08/...ne-and-or/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016