{"id":115442,"date":"2020-07-15T06:42:11","date_gmt":"2020-07-15T06:42:11","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=10805"},"modified":"2020-07-15T06:42:11","modified_gmt":"2020-07-15T06:42:11","slug":"python-ternary-elif","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/07\/15\/python-ternary-elif\/","title":{"rendered":"Python Ternary Elif"},"content":{"rendered":"<p class=\"has-luminous-vivid-amber-background-color has-background\"><strong>Summary<\/strong>: To use an elif branch in the ternary operator, use another ternary operator as the result of the else branch (nested ternary operator). The nested ternary operator <code>x if c0 else y if c1 else z<\/code> returns <code>x<\/code> if condition <code>c0<\/code> is met, else if (elif) condition <code>c1<\/code> is met, it returns <code>y<\/code>, else it returns <code>z<\/code>.<\/p>\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/elif-1024x576.jpg\" alt=\"Python Ternary Elif\" class=\"wp-image-10815\" width=\"768\" height=\"432\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/elif-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/elif-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/elif-768x432.jpg 768w\" sizes=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/figure>\n<p><strong>Problem<\/strong>: You may have seen the ternary operator <code>x if c else y<\/code>. Is there a similar ternary operator with an additional elif statement? In pseudocode, you want something like:<\/p>\n<pre class=\"wp-block-preformatted\"><code># Pseudocode<\/code>\n<code>x if c <strong>elif y0<\/strong> else y1<\/code><\/pre>\n<p>In other words: <em>What&#8217;s the best way of extending the ternary operator to what you may call a &#8220;quaternary&#8221; operator?<\/em><\/p>\n<p><strong>Background<\/strong>: The most basic ternary operator <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><strong><em><a href=\"https:\/\/blog.finxter.com\/python-one-line-ternary\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line Ternary\">Learn more about the ternary operator in our detailed blog article!<\/a><\/em><\/strong><\/p>\n<p><strong>Example<\/strong>: Say, you want to write the following if-then-else condition in a single line of code:<\/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\n>>> if x > 42:\n>>> print(\"no\")\n>>> elif x == 42:\n>>> print(\"yes\")\n>>> else:\n>>> print(\"maybe\")\nyes<\/pre>\n<p>The elif branch wins: you print the output <code>\"yes\"<\/code> to the shell. <\/p>\n<p>But how to do it in a single line of code? Just use the ternary operator with an elif statement won&#8217;t work (it&#8217;ll throw a syntax error):<\/p>\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/image-4.png\" alt=\"\" class=\"wp-image-10807\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/image-4.png 724w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/image-4-300x36.png 300w\" sizes=\"(max-width: 724px) 100vw, 724px\" \/><\/figure>\n<h2>Method: Nested Ternary Operator<\/h2>\n<p>The answer is simple: nest two ternary operators like so:<\/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=\"\">>>> print(\"no\") if x > 42 else print(\"yes\") if x == 42 else print(\"maybe\")\nyes<\/pre>\n<p>If the value x is larger than 42, we print &#8220;no&#8221; to the shell. Otherwise, we execute the remainder of the code (which is a ternary operator by itself). If the value x is equal to 42, we print &#8220;yes&#8221;, otherwise &#8220;maybe&#8221;.<\/p>\n<p>So by nesting multiple ternary operators, we can greatly increase our Python one-liner power!<\/p>\n<p><strong>Try it yourself:<\/strong><\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/a19986f70c\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen=\"\" width=\"100%\" height=\"356\" frameborder=\"0\"><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Which method is more concise? Count the number of characters (or write a small script that does it for you ;))!<\/em><\/p>\n<h2>Python Ternary Multiple Elif<\/h2>\n<p>In the previous example, you&#8217;ve seen how a nested ternary operator semantically adds an elif branch. In theory, you can add an arbitrary number of elif branches by nesting more and more ternary operators:<\/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: If ... Elif ... Else\nx = 42\nif x > 42: y = 1\nelif x == 42: y = 2\nelif x == 12: y = 3\nelse: y = 4\nprint(y)\n# 2 # Method 2: Nested Ternary Operator\ny = 1 if x > 42 else 2 if x == 42 else 3 if x == 12 else 4\nprint(y)\n# 2\n<\/pre>\n<p>However, readability suffers badly and you shouldn&#8217;t do anything of the sort. A simple mult-line <code>if ... elif ... elif ... else<\/code> statement is better! <\/p>\n<h2>Discussion<\/h2>\n<p>However, even if the nested ternary operator is more concise than an if-elif-else statement, it&#8217;s not recommended because of readability of your code. Most programmers don&#8217;t have any trouble understanding a simple if-elif-else statement. But a nested ternary operator is an advanced-level piece of Python code and especially beginners will struggle understanding it. <\/p>\n<p><strong>So, it&#8217;s great that you&#8217;ve expanded your One-Liner Superpower. But you should use it wisely!<\/strong><\/p>\n<h2>Related Video: If-Then-Else in One Line of Python Code<\/h2>\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=\"If-Then-Else in One Line Python\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/ZGUAaQiO06Y?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\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:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\"><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:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\"><em>Get your Python One-Liners Now!!<\/em><\/a><\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Summary: To use an elif branch in the ternary operator, use another ternary operator as the result of the else branch (nested ternary operator). The nested ternary operator x if c0 else y if c1 else z returns x if condition c0 is met, else if (elif) condition c1 is met, it returns y, else [&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-115442","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\/115442","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=115442"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/115442\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=115442"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=115442"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=115442"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}