Sick Gaming
[Tut] Python One Line If Not None - Printable Version

+- Sick Gaming (https://www.sickgaming.net)
+-- Forum: Programming (https://www.sickgaming.net/forum-76.html)
+--- Forum: Python (https://www.sickgaming.net/forum-83.html)
+--- Thread: [Tut] Python One Line If Not None (/thread-97198.html)



[Tut] Python One Line If Not None - xSicKxBot - 09-11-2020

Python One Line If Not None

<div><p class="has-pale-cyan-blue-background-color has-background">To assign the result of a function <code>get_value()</code> to variable <code>x</code> if it is different from <code>None</code>, use the Walrus operator <code>if tmp := get_value(): x = tmp</code> within a single-line if block. The Walrus operator assigns the function’s return value to the variable <code>tmp</code> and returns it at the same time, so that you can check and assign it to variable <code>x</code> subsequently. </p>
<p><strong>Problem</strong>: How to assign a value to a variable if it is not equal to <code>None</code>—using only a single line of Python code? </p>
<p><strong>Example</strong>: Say, you want to assign the return value of a function get_value(), but only if it doesn’t return None. Otherwise, you want to leave the value as it is. Here’s a code example:</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="">import random def get_value(): if random.random()>0.5: return None return 1 # Naive approach:
x = 42
tmp = get_value()
if tmp != None: x = tmp
print(tmp)</pre>
<p>While this works, you need to execute the function <code>get_value()</code> twice which is not optimal. An alternative would be to assign the result of the <code>get_value()</code> function to a temporary variable to avoid repeated function execution:</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="">x = 42
temp = get_value()
if temp != None: x = temp
print(x)</pre>
<p>However, this seems clunky and ineffective. Is there a better way?</p>
<p>Let’s have an overview of the one-liners that conditionally assign a value to a given variable:</p>
<p> <iframe height="700px" width="100%" src="https://repl.it/@finxter/CrookedLivelyLocks?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"></iframe> </p>
<p><em><strong>Exercise</strong>: Run the code. Does it always generate the same result? </em></p>
<h2>Method 1: Ternary Operator + Semicolon</h2>
<p>The most basic <a href="https://blog.finxter.com/python-one-line-ternary/" target="_blank" rel="noreferrer noopener" title="Python One Line Ternary">ternary operator</a> <code>x if c else y</code> consists of three operands <code>x</code>, <code>c</code>, and <code>y</code>. It is an expression with a return value. The ternary operator returns <code>x</code> if the Boolean expression <code>c</code> evaluates to <code>True</code>. Otherwise, if the expression <code>c</code> evaluates to <code>False</code>, the ternary operator returns the alternative <code>y</code>.</p>
<p>You can use the ternary operator to solve this problem in combination with the <a href="https://blog.finxter.com/how-to-execute-multiple-lines-in-a-single-line-python-from-command-line/" target="_blank" rel="noreferrer noopener" title="How to Execute Multiple Lines in a Single Line Python From Command-Line?">semicolon to write multiple lines of code </a>as a Python one-liner. </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=""># Method 1
tmp = get_value(); x = tmp if tmp else x</pre>
<p>You cannot run the <code>get_value()</code> function twice—to check whether it returns <code>True</code> and to assign the return value to the variable <code>x</code>. Why? Because it’s nondeterministic and may return different values for different executions.</p>
<p>Therefore, the following code would be a blunt mistake:</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="">x = get_value() if get_value() else x</pre>
<p>The variable <code>x</code> may still be <code>None</code>—even after the ternary operator has seemingly checked the condition. </p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="The Python Ternary Operator -- And a Surprising One-Liner Hack" width="1400" height="788" src="https://www.youtube.com/embed/9XXcUHXrqZ4?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p><strong>Related articles:</strong></p>
<ul>
<li><a href="https://blog.finxter.com/python-one-line-ternary/" target="_blank" rel="noreferrer noopener" title="Python One Line Ternary">Python Ternary</a></li>
<li><a href="https://blog.finxter.com/if-then-else-in-one-line-python/" target="_blank" rel="noreferrer noopener" title="If-Then-Else in One Line Python [Video + Interactive Code Shell]">Python Single-Line If Statement</a></li>
<li><a href="https://blog.finxter.com/python-semicolons-how-they-work-and-why-haters-tell-you-to-avoid-them/" target="_blank" rel="noreferrer noopener" title="Python Semicolons: How They Work and Why Haters Tell You to Avoid Them">Python Semicolon</a></li>
</ul>
<h2>Method 2: Walrus + One-Line-If</h2>
<p>A beautiful extension of <a href="https://blog.finxter.com/how-to-check-your-python-version/" title="How to Check Your Python Version? A Helpful Guide" target="_blank" rel="noreferrer noopener">Python 3.8</a> is the <a href="https://blog.finxter.com/python-3-8-walrus-operator-assignment-expression/" title="Python 3.8 Walrus Operator (Assignment Expression)" target="_blank" rel="noreferrer noopener">Walrus operator</a>. <strong><em>The Walrus operator <code>:=</code> is an assignment operator with return value.</em></strong> Thus, it allows you to check a condition and assign a value at the same time:</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="">
# Method 2
if tmp := get_value(): x = tmp</pre>
<p>This is a very clean, readable, and Pythonic way. Also, you don’t have the redundant identity assignment in case the if condition is not fulfilled.</p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="Python 3.8 Walrus Operator (Assignment Expression)" width="1400" height="788" src="https://www.youtube.com/embed/RGTjHAzIv7w?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p> <strong>Related Article:</strong> <a href="https://blog.finxter.com/python-3-8-walrus-operator-assignment-expression/" target="_blank" rel="noreferrer noopener" title="Python 3.8 Walrus Operator (Assignment Expression)">The Walrus Operator in Python 3.8</a></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 loading="lazy" 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/uploads/2020/06/3D_cover-300x277.jpg 300w, https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-768x708.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/09/10/python-one-line-if-not-none/