{"id":117807,"date":"2020-09-10T10:46:10","date_gmt":"2020-09-10T10:46:10","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=12900"},"modified":"2020-09-10T10:46:10","modified_gmt":"2020-09-10T10:46:10","slug":"python-one-line-if-not-none","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/09\/10\/python-one-line-if-not-none\/","title":{"rendered":"Python One Line If Not None"},"content":{"rendered":"<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&#8217;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>\n<p><strong>Problem<\/strong>: How to assign a value to a variable if it is not equal to <code>None<\/code>&#8212;using only a single line of Python code? <\/p>\n<p><strong>Example<\/strong>: Say, you want to assign the return value of a function get_value(), but only if it doesn&#8217;t return None. Otherwise, you want to leave the value as it is. Here&#8217;s a code example:<\/p>\n<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:\nx = 42\ntmp = get_value()\nif tmp != None: x = tmp\nprint(tmp)<\/pre>\n<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>\n<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\ntemp = get_value()\nif temp != None: x = temp\nprint(x)<\/pre>\n<p>However, this seems clunky and ineffective. Is there a better way?<\/p>\n<p>Let&#8217;s have an overview of the one-liners that conditionally assign a value to a given variable:<\/p>\n<p> <iframe loading=\"lazy\" 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>\n<p><em><strong>Exercise<\/strong>: Run the code. Does it always generate the same result? <\/em><\/p>\n<h2>Method 1: Ternary Operator + Semicolon<\/h2>\n<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>\n<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>\n<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\ntmp = get_value(); x = tmp if tmp else x<\/pre>\n<p>You cannot run the <code>get_value()<\/code> function twice&#8212;to check whether it returns <code>True<\/code> and to assign the return value to the variable <code>x<\/code>. Why? Because it&#8217;s nondeterministic and may return different values for different executions.<\/p>\n<p>Therefore, the following code would be a blunt mistake:<\/p>\n<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>\n<p>The variable <code>x<\/code> may still be <code>None<\/code>&#8212;even after the ternary operator has seemingly checked the condition. <\/p>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" 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>\n<\/div>\n<\/figure>\n<p><strong>Related articles:<\/strong><\/p>\n<ul>\n<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>\n<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>\n<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>\n<\/ul>\n<h2>Method 2: Walrus + One-Line-If<\/h2>\n<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>\n<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=\"\">\n# Method 2\nif tmp := get_value(): x = tmp<\/pre>\n<p>This is a very clean, readable, and Pythonic way. Also, you don&#8217;t have the redundant identity assignment in case the if condition is not fulfilled.<\/p>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" 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>\n<\/div>\n<\/figure>\n<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>\n<h2>Python One-Liners Book<\/h2>\n<p><strong>Python programmers will improve their computer science skills with these useful one-liners.<\/strong><\/p>\n<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\" decoding=\"async\" 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=\"auto, (max-width: 512px) 100vw, 512px\" \/><\/a><\/figure>\n<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 &#8220;one-liners&#8221;: concise statements of useful functionality packed into a single line of code. You&#8217;ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.<\/p>\n<p>The book&#8217;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&#8217;ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You&#8217;ll also learn how to:<\/p>\n<p><strong>\u2022<\/strong>&nbsp;&nbsp;Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning<br \/><strong>\u2022<\/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>\u2022<\/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>\n<p>By the end of the book, you&#8217;ll know how to write Python at its most refined, and create concise, beautiful pieces of &#8220;Python art&#8221; in merely a single line.<\/p>\n<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>\n","protected":false},"excerpt":{"rendered":"<p>To assign the result of a function get_value() to variable x if it is different from None, use the Walrus operator if tmp := get_value(): x = tmp within a single-line if block. The Walrus operator assigns the function&#8217;s return value to the variable tmp and returns it at the same time, so that you [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-117807","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/117807","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=117807"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/117807\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=117807"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=117807"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=117807"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}