{"id":116727,"date":"2020-08-15T08:48:01","date_gmt":"2020-08-15T08:48:01","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=11891"},"modified":"2020-08-15T08:48:01","modified_gmt":"2020-08-15T08:48:01","slug":"how-to-write-multiple-statements-on-a-single-line-in-python","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/08\/15\/how-to-write-multiple-statements-on-a-single-line-in-python\/","title":{"rendered":"How to Write Multiple Statements on a Single Line in Python?"},"content":{"rendered":"<p><strong>Problem<\/strong>: Given multiple Python statements. How to write them as a <a href=\"https:\/\/blog.finxter.com\/python-one-line-x\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line X\">Python One-Liner<\/a>?<\/p>\n<p><strong>Example<\/strong>: Consider the following example of four statements in a block with uniform <a href=\"https:\/\/blog.finxter.com\/pep-8-hanging-indentation-and-closing-brackets-in-python\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"PEP 8: Hanging Indentation and Closing Brackets in Python\">indentation<\/a>:<\/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=\"\">a = 1\nb = 2\nc = a + b\nprint(c)<\/pre>\n<p>Each of the four statements is written in a separate line in a <a href=\"https:\/\/blog.finxter.com\/best-python-ide\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Best Python IDE and Code Editors [Ultimate Guide]\">code editor<\/a>&#8212;this is the normal procedure. However, what if you want to <a href=\"https:\/\/pythononeliners.com\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/pythononeliners.com\/\">one-linerize<\/a> those:<\/p>\n<p><strong><em>How to write all four statements in a single line of code?<\/em><\/strong><\/p>\n<p><strong>Solution<\/strong>: The answer is simple if all statements have a uniform indentation and there&#8217;s no <a href=\"https:\/\/blog.finxter.com\/how-to-write-a-nested-for-loop-in-one-line-python\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"How to Write a Nested For Loop in One Line Python?\">nested block<\/a>. In this case, you can use the semicolon as a separator between the statements:<\/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=\"\">a = 1; b = 2; c = a + b; print(c)<\/pre>\n<p>Let&#8217;s do some <a href=\"https:\/\/finxter.com\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/finxter.com\/\">practice testing<\/a> to learn and improve your Python skills:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/a8d4624986\" width=\"100%\" height=\"356\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: one-linerize the given code! Run the code and check if the one-liner does the same as the original code!<\/em><\/p>\n<h2>Indented Block<\/h2>\n<p>While this works beautifully, if all statements are <em>not indented<\/em>&#8212;does it still work if you have an indentation block that starts with the colon <code>:<\/code> symbol after <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]\"><code>if<\/code>, <code>elif<\/code>, <code>else<\/code><\/a>, <code><a href=\"https:\/\/blog.finxter.com\/python-one-line-for-loop-a-simple-tutorial\/\" title=\"Python One Line For Loop [A Simple Tutorial]\">for<\/a><\/code>, <code><a href=\"https:\/\/blog.finxter.com\/python-one-line-while-loop-a-simple-tutorial\/\" title=\"Python One Line While Loop [A Simple Tutorial]\">while<\/a><\/code>, or <code><a href=\"https:\/\/blog.finxter.com\/python-one-line-exception-handling\/\" title=\"Python One Line Exception Handling\">try\/except<\/a><\/code> statements?<\/p>\n<p>Here&#8217;s an example of such a block:<\/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=\"\">for i in range(10): c = i ** 2 print (c)<\/pre>\n<p>You try the following one-liner using the semicolon as a separator between the two statements in the block<\/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=\"\">for i in range(10): c = i ** 2; print(c) '''\n0\n1\n4\n9\n16\n25\n36\n49\n64\n81 '''<\/pre>\n<p>This works beautifully and Python understands what you are trying to do. However, if you have nested indentation blocks, this doesn&#8217;t work anymore. <\/p>\n<p>Consider the following 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=\"\">for i in range(3): for j in range(3): print(i, j)<\/pre>\n<p>If you write this in a single line, Python throws a syntax error:<\/p>\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/08\/image.png\" alt=\"\" class=\"wp-image-11892\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/08\/image.png 842w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/08\/image-300x178.png 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/08\/image-768x456.png 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/08\/image-150x89.png 150w\" sizes=\"(max-width: 842px) 100vw, 842px\" \/><\/figure>\n<p>While you can discuss if this makes sense or not&#8212;given that the syntax is not ambiguous here&#8212;it doesn&#8217;t change the fact: <strong><em>nested block cannot be one-linerized in a straightforward way.<\/em><\/strong> But this doesn&#8217;t prevent us from doing it, right?<\/p>\n<h2>Nested Indentation Blocks<\/h2>\n<p><a href=\"https:\/\/blog.finxter.com\/how-to-execute-multiple-lines-in-a-single-line-python-from-command-line\/\" title=\"How to Execute Multiple Lines in a Single Line Python From Command-Line?\" target=\"_blank\" rel=\"noreferrer noopener\">Read the following article to learn how to compress multiple lines of code into a single line!<\/a><\/p>\n<p><strong>Summary<\/strong>: To make a Python one-liner out of any multi-line Python script, replace the new lines with a new line character <code>'\\n'<\/code> and pass the result into the <code>exec(...)<\/code> function. You can run this script from the outside (command line, shell, terminal) by using the command <code>python -c \"exec(...)\"<\/code>.<\/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=\"[Don&#039;t Do This At Home] How To One-Linerize Every Multi-Line Python Script &amp; Run It From The Shell\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/zGJgctQEkSU?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<p>This method is very powerful and it allows you to compress any complicated multi-line script in a single line of Python code!<\/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>Problem: Given multiple Python statements. How to write them as a Python One-Liner? Example: Consider the following example of four statements in a block with uniform indentation: a = 1 b = 2 c = a + b print(c) Each of the four statements is written in a separate line in a code editor&#8212;this is [&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-116727","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\/116727","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=116727"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/116727\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=116727"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=116727"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=116727"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}