{"id":79309,"date":"2020-07-04T09:00:49","date_gmt":"2020-07-04T03:30:49","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=79309"},"modified":"2020-07-04T09:00:49","modified_gmt":"2020-07-04T03:30:49","slug":"ternary-operator-in-python","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/ternary-operator-in-python\/","title":{"rendered":"Ternary Operator in Python with Examples"},"content":{"rendered":"<p>Python\u2019s <strong>if-else<\/strong> statements are very easy to write and read. But they come with a downside. That is, if you want to print something based on some condition, you need 4 lines to do that.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">x = 10\nif x &gt; 5:\n    print(\"greater\")\nelse:\n    print(\"smaller\")\n<\/pre>\n<p>That\u2019s an awful lot of lines for such a simple operation. What\u2019s the solution, you ask? <strong>Ternary operators<\/strong> in Python!<\/p>\n<p>Let&#8217;s learn more about Python ternary operators.<\/p>\n<h3>What is Ternary Operator in Python?<\/h3>\n<p>The ternary operator in Python is nothing but a one-line version of the if-else statement. It provides a way to write <strong>conditional statements<\/strong> in a <strong>single line<\/strong>, replacing the <strong>multi-line if-else syntax<\/strong>.<\/p>\n<p><strong>Syntax of Python ternary operator<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&lt;true_value&gt; if &lt;conditional_expression&gt; else &lt;false_value&gt;<\/pre>\n<p>Python ternary operator works with three operands:<\/p>\n<p><strong>1. conditional_expression:<\/strong> This is a boolean condition that evaluates to either true or false.<br \/>\n<strong>2. true_value:<\/strong> The value returned by the ternary operator if the conditional_expression evaluates to True.<br \/>\n<strong>3. false_value:<\/strong> The value returned by the ternary operator if the conditional_expression evaluates to False.<\/p>\n<p><strong>Example 1: Conditional expression is a boolean value<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; nice_weather = True\n&gt;&gt;&gt; print(\"Go out for a walk\" if nice_weather else \"watch a movie at home\")\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Go out for a walk<\/div>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; nice_weather = False\n&gt;&gt;&gt; print(\"Go out for a walk\" if nice_weather else \"watch a movie at home\")\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">watch a movie at home<\/div>\n<p><strong>Example 2: Conditional expression is a boolean expression<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; num = 12\n&gt;&gt;&gt; print(\"Even\" if num % 2 == 0 else \"Odd\")<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Even<\/div>\n<p><strong>Example 3: Variable assignment<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; a = 10\n&gt;&gt;&gt; b = 5\n&gt;&gt;&gt; largest = a if a &gt; b else b\n&gt;&gt;&gt; print(largest)\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">10<br \/>\n&gt;&gt;&gt;<\/div>\n<p>The variable largest gets the value of:<\/p>\n<ul>\n<li><strong>a,<\/strong> if a is greater than b<\/li>\n<li><strong>b,<\/strong> if a is not greater than b<\/li>\n<\/ul>\n<h3>The ternary operator using Tuple<\/h3>\n<p>Another way to implement ternary operation in Python is by using a <strong>tuple<\/strong>. This is a simple replacement for the if-else ternary operator.<\/p>\n<p><strong>Syntax<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">(false_value, true_value)[conditional_expression]<\/pre>\n<p>In this case, the <strong>false_value<\/strong> and <strong>true_value<\/strong> form the two elements of the tuple. And the <strong>conditional_expression<\/strong> goes within the square bracket notation in place of an <strong>index<\/strong>. This works simply because the value of True is 1 and that of False is 0.<\/p>\n<p>Therefore:<\/p>\n<ul>\n<li>If the conditional_expression evaluates to True, it\u2019s value becomes .<\/li>\n<li>Then the element at index 1 gets returned by the ternary expression.<\/li>\n<li>And if the conditional_expression evaluates to False, it\u2019s value becomes 0.<\/li>\n<li>Then the element at index 0 gets returned.<\/li>\n<\/ul>\n<p>Be sure to put the <strong>false_value<\/strong> at index 0 and <strong>true_value<\/strong> at index 1 in the tuple.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; a = 10\n&gt;&gt;&gt; b = 5\n&gt;&gt;&gt; largest = (b, a)[a &gt; b]\n&gt;&gt;&gt; print(largest)\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">10<\/div>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; nice_weather = True\n&gt;&gt;&gt; print((\"Watch a movie at home\", \"Go out for a walk\")[nice_weather])\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Go out for a walk<br \/>\n&gt;&gt;&gt;<\/div>\n<p>We can extend this syntax and use a <strong>list<\/strong> or a <strong>dictionary<\/strong> instead of a tuple.<\/p>\n<h3>The syntax for ternary operation using a list<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">[false_value, true_value][conditional_expression]<\/pre>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; a = 10\n&gt;&gt;&gt; b = 5\n&gt;&gt;&gt; largest = [b, a][a &gt; b]\n&gt;&gt;&gt; print(largest)\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">10<\/div>\n<h3>Syntax for ternary operation using a dictionary<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">{True: true_value, False: false_value}[conditional_expression]<\/pre>\n<p>Here, the true_value and false_value become the values of the keys True and False respectively. If the <strong>conditional_expression<\/strong> evaluates to True, the value corresponding to True gets <strong>returned<\/strong>. Else, the value corresponding to False gets returned.<\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; nice_weather = False\n&gt;&gt;&gt; s = {True: \"Go out for a walk\", False: \"Watch a movie at home\"}[nice_weather]\n&gt;&gt;&gt; print(s)\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Watch a movie at home<br \/>\n&gt;&gt;&gt;<\/div>\n<h3>Summary<\/h3>\n<p>This brings us to the end of the article. We learned about various ways to implement <strong>ternary operations<\/strong> in Python. We saw how ternary operators increase the code <strong>readability<\/strong> and make it <strong>compact<\/strong>.<\/p>\n<p>Make use of ternary operators in your code to make it more <strong>\u201cPythonic\u201d<\/strong>!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python\u2019s if-else statements are very easy to write and read. But they come with a downside. That is, if you want to print something based on some condition, you need 4 lines to do&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":79375,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1053],"tags":[3003,3004,3005],"class_list":["post-79309","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-python-ternary","tag-python-ternary-operator","tag-ternary-operator-in-python"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Ternary Operator in Python with Examples - TechVidvan<\/title>\n<meta name=\"description\" content=\"Learn what are ternary operators in python and its uses. Check the syntax of python ternary operator and examples for better understanding.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/ternary-operator-in-python\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Ternary Operator in Python with Examples - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Learn what are ternary operators in python and its uses. Check the syntax of python ternary operator and examples for better understanding.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/ternary-operator-in-python\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2020-07-04T03:30:49+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/ternary-operator-in-python.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"802\" \/>\n\t<meta property=\"og:image:height\" content=\"420\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Ternary Operator in Python with Examples - TechVidvan","description":"Learn what are ternary operators in python and its uses. Check the syntax of python ternary operator and examples for better understanding.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/ternary-operator-in-python\/","og_locale":"en_US","og_type":"article","og_title":"Ternary Operator in Python with Examples - TechVidvan","og_description":"Learn what are ternary operators in python and its uses. Check the syntax of python ternary operator and examples for better understanding.","og_url":"https:\/\/techvidvan.com\/tutorials\/ternary-operator-in-python\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2020-07-04T03:30:49+00:00","og_image":[{"width":802,"height":420,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/ternary-operator-in-python.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/ternary-operator-in-python\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/ternary-operator-in-python\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Ternary Operator in Python with Examples","datePublished":"2020-07-04T03:30:49+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/ternary-operator-in-python\/"},"wordCount":496,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/ternary-operator-in-python\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/ternary-operator-in-python.jpg","keywords":["Python Ternary","python ternary operator","Ternary Operator in Python"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/ternary-operator-in-python\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/ternary-operator-in-python\/","url":"https:\/\/techvidvan.com\/tutorials\/ternary-operator-in-python\/","name":"Ternary Operator in Python with Examples - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/ternary-operator-in-python\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/ternary-operator-in-python\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/ternary-operator-in-python.jpg","datePublished":"2020-07-04T03:30:49+00:00","description":"Learn what are ternary operators in python and its uses. Check the syntax of python ternary operator and examples for better understanding.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/ternary-operator-in-python\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/ternary-operator-in-python\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/ternary-operator-in-python\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/ternary-operator-in-python.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/ternary-operator-in-python.jpg","width":802,"height":420,"caption":"ternary operator in python"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/ternary-operator-in-python\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Ternary Operator in Python with Examples"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/79309","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=79309"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/79309\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/79375"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=79309"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=79309"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=79309"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}