{"id":115311,"date":"2020-07-09T07:17:52","date_gmt":"2020-07-09T07:17:52","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=10612"},"modified":"2020-07-09T07:17:52","modified_gmt":"2020-07-09T07:17:52","slug":"python-one-line-x","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/07\/09\/python-one-line-x\/","title":{"rendered":"Python One Line X"},"content":{"rendered":"<p>This is a running document in which I&#8217;ll answer all questions regarding the single line of Python code. If you want to check out my book <a href=\"https:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\">&#8220;Python One-Liners&#8221;<\/a> and <strong>become a one-liner wizard<\/strong>&#8212;be my guest! <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/12.0.0-1\/72x72\/1f609.png\" alt=\"\ud83d\ude09\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <\/p>\n<p>Let&#8217;s get started!<\/p>\n<h2>Python One Line If Without Else<\/h2>\n<h2>Python One Line If Else<\/h2>\n<h2>Python One Line Elif<\/h2>\n<h2>Python One Line Function<\/h2>\n<h2>Python One Line For Loop<\/h2>\n<h2>Python One Line For Loop If<\/h2>\n<h2>Python One Line For Loop Lambda<\/h2>\n<h2>Python One Line While Loop<\/h2>\n<h2>Python One Line HTTP Web Server<\/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=\"The Top 18 Best Python Tricks\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/a9nmyrek3qk?start=737&#038;feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<p>Want to create your own webserver in a <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-one-liners-the-ultimate-collection\/\" target=\"_blank\">single line of Python code<\/a>? No problem, just use this command in your shell:<\/p>\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/05\/image-61.png\" alt=\"\" class=\"wp-image-8636\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/05\/image-61.png 743w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/05\/image-61-300x124.png 300w\" sizes=\"(max-width: 743px) 100vw, 743px\" \/><\/figure>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"shell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">$ python -m http.server 8000<\/pre>\n<p>The terminal will tell you:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"shell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">Serving HTTP on 0.0.0.0 port 8000<\/pre>\n<p>To shut down your webserver, kill the Python program with <code>CTRL+c<\/code>.<\/p>\n<p>This works if you&#8217;ve <strong>Python 3<\/strong> installed on your system. To check your version, use the command <code><a href=\"https:\/\/blog.finxter.com\/how-to-check-your-python-version\/\">python --version<\/a><\/code> in your shell. <\/p>\n<p><em>You can run this command in your Windows Powershell, Win Command Line, MacOS Terminal, or Linux Bash Script.<\/em><\/p>\n<p>You can see in the screenshot that the server runs on your local host listening on port 8000 (the standard HTTP port to serve web requests).<\/p>\n<p><em><strong>Note<\/strong>: The IP address is <strong>NOT<\/strong> 0.0.0.0&#8212;this is an often-confused mistake by many readers. Instead, your webserver listens at your &#8220;local&#8221; IP address 127.0.0.1 on port 8000. Thus, only web requests issued on your computer will arrive at this port. The webserver is NOT visible to the outside world.<\/em><\/p>\n<p><strong>Python 2<\/strong>: To run the same simple webserver on Python 2, you need to use another command using <a href=\"https:\/\/docs.python.org\/2\/library\/simplehttpserver.html\" target=\"_blank\" rel=\"noreferrer noopener\"><code>SimpleHTTPServer<\/code> <\/a>instead of <code>http<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"shell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">$ python -m SimpleHTTPServer 8000\nServing HTTP on 0.0.0.0 port 8000 ...<\/pre>\n<p>If you want to start your webserver from within your Python script, no problem:<\/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 http.server\nimport socketserver PORT = 8000 Handler = http.server.SimpleHTTPRequestHandler with socketserver.TCPServer((\"\", PORT), Handler) as httpd: print(\"serving at port\", PORT) httpd.serve_forever()<\/pre>\n<p>You can execute this in our online Python browser (yes, you&#8217;re creating a local webserver in the browser&#8212;how cool is that)!<\/p>\n<figure><iframe loading=\"lazy\" src=\"https:\/\/repl.it\/@finxter\/webserver?lite=true\" allowfullscreen=\"true\" width=\"100%\" height=\"1000px\"><\/iframe><\/figure>\n<p>This code comes from the <a rel=\"noreferrer noopener\" href=\"https:\/\/docs.python.org\/3\/library\/http.server.html\" target=\"_blank\">official Python documentation<\/a>&#8212;feel free to read more if you&#8217;re interested in setting up the server (most of the code is relatively self-explanatory). <\/p>\n<p><strong>Source<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-one-liner-webserver\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One-Liner Webserver HTTP\">Python One-Liner Webserver HTTP<\/a><\/p>\n<h2>Python One Line Webshell<\/h2>\n<h2>Python One Line Write String to File<\/h2>\n<h2>Python One Line Quine<\/h2>\n<h2>Python One Line Quicksort<\/h2>\n<p>In this one-liner tutorial, you\u2019ll learn about the popular sorting algorithm <a href=\"https:\/\/en.wikipedia.org\/wiki\/Quicksort\">Quicksort<\/a>. Surprisingly, a single line of Python code is all you need to write the Quicksort algorithm!<\/p>\n<p><strong>Problem<\/strong>: Given a list of numerical values (integer or float). Sort the list in a single line of Python code using the popular <a href=\"https:\/\/blog.finxter.com\/python-one-line-quicksort\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line Quicksort\">Quicksort <\/a>algorithm!<\/p>\n<p><strong>Example<\/strong>: You have list <code>[4, 2, 1, 42, 3]<\/code>. You want to sort the list in ascending order to obtain the new list <code>[1, 2, 3, 4, 42]<\/code>. <\/p>\n<p><strong>Short answer<\/strong>: The following one-liner solution sorts the list recursively using the Quicksort algorithm: <\/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=\"\">q = lambda l: q([x for x in l[1:] if x &lt;= l[0]]) + [l[0]] + q([x for x in l if x > l[0]]) if l else []<\/pre>\n<p>You can try it yourself using the following interactive code shell:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/82f77b2571\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen=\"\" width=\"100%\" height=\"356\" frameborder=\"0\"><\/iframe> <\/p>\n<p>Now, let&#8217;s dive into some details!<\/p>\n<p>The following introduction is based on my new book <a href=\"https:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\"><strong>&#8220;Python One-Liners&#8221;<\/strong><\/a> <em>(Amazon Link)<\/em> that teaches you the power of the single line of code (use it wisely)!<\/p>\n<figure class=\"wp-block-image size-medium is-resized\"><a href=\"https:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\"><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=\"256\" height=\"236\" 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: 256px) 100vw, 256px\" \/><\/a><\/figure>\n<p><strong>Introduction<\/strong>: <a href=\"https:\/\/blog.finxter.com\/the-quicksort-algorithm-in-one-line-python\/\" title=\"The Shortest Quicksort Implementation in Python\" target=\"_blank\" rel=\"noreferrer noopener\">Quicksort <\/a>is not only a popular question in many <a href=\"https:\/\/blog.finxter.com\/python-interview-questions\/\" title=\"They Use These 15+ Python Interview Questions To Fail You \u2026 (And What You Can Do About It)\" target=\"_blank\" rel=\"noreferrer noopener\">code interviews<\/a> \u2013 asked by Google, Facebook, and Amazon \u2013 but also a practical <a href=\"https:\/\/blog.finxter.com\/python-list-sort\/\" title=\"Python List sort() \u2013 The Ultimate Guide\" target=\"_blank\" rel=\"noreferrer noopener\">sorting <\/a>algorithm that is fast, concise, and readable. Because of its beauty, you won\u2019t find many introduction to algorithm classes which don\u2019t discuss the Quicksort algorithm.<\/p>\n<p><strong>Overview<\/strong>: Quicksort sorts a list by <a href=\"https:\/\/blog.finxter.com\/recursion\/\" title=\"Recursion: A Helpful Guide in Python\" target=\"_blank\" rel=\"noreferrer noopener\">recursively <\/a>dividing the big problem (sorting the list) into smaller problems (sorting two smaller lists) and combining the solutions from the smaller problems in a way that it solves the big problem. In order to solve each smaller problem, the same strategy is used recursively: the smaller problems are divided into even smaller subproblems, solved separately, and combined. Because of this strategy, Quicksort belongs to the class of \u201cDivide and Conquer\u201d algorithms.<\/p>\n<p><strong>Algorithm<\/strong>: The main idea of Quicksort is to select a pivot element and then placing all elements that are larger or equal than the pivot element to the right and all elements that are smaller than the pivot element to the left. Now, you have divided the big problem of sorting the list into two smaller subproblems: sorting the right and the left partition of the list. What you do now is to repeat this procedure recursively until you obtain a list with zero elements. This list is already sorted, so the recursion terminates. <\/p>\n<p>The following Figure shows the Quicksort algorithm in action:<\/p>\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2019\/06\/image-11.png\" alt=\"\" class=\"wp-image-3689\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2019\/06\/image-11.png 604w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2019\/06\/image-11-300x169.png 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2019\/06\/image-11-100x56.png 100w\" sizes=\"(max-width: 604px) 100vw, 604px\" \/><\/figure>\n<p><strong>Figure<\/strong>: The Quicksort algorithm selects a pivot element, splits up the list into (i) an unsorted sublist with all elements that are smaller or equal than the pivot, and (ii) an unsorted sublist with all elements that are larger than the pivot. Next, the Quicksort algorithm is called recursively on the two unsorted sublists to sort them. As soon as the sublists contain maximally one element, they are sorted by definition \u2013 the recursion ends. At every recursion level, the three sublists (left, pivot, right) are concatenated before the resulting list is handed to the higher recursion level.<\/p>\n<p><em>You create a function <code>q<\/code> which implements the Quicksort algorithm in a single line of Python code \u2013 and thus sorts any argument given as a list of integers.<\/em><\/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=\"\">## The Data\nunsorted = [33, 2, 3, 45, 6, 54, 33] ## The One-Liner\nq = lambda l: q([x for x in l[1:] if x &lt;= l[0]]) + [l[0]] + q([x for x in l if x > l[0]]) if l else [] ## The Result\nprint(q(unsorted))<\/pre>\n<p>What is the output of this 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=\"\">## The Result\nprint(q(unsorted))\n# [2, 3, 6, 33, 33, 45, 54]<\/pre>\n<h2>Python One Line With Statement<\/h2>\n<h2>Python One Line Exception Handling<\/h2>\n<h2>Python One Line Try Except<\/h2>\n<h2>Python One Line Execute<\/h2>\n<h2>Python One Line Reverse Shell<\/h2>\n<h2>Python One Line Read File<\/h2>\n<h2>Python One Line Return If<\/h2>\n<h2>Python One Line Regex Match<\/h2>\n<h2>Python One Line Recursion<\/h2>\n<h2>Python One Line Regex<\/h2>\n<h2>Python One Line Read File to List<\/h2>\n<h2>Python One Line Read Stdin<\/h2>\n<h2>Python One Line Replace<\/h2>\n<h2>Python One Line Ternary<\/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=\"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>Ternary<\/strong> (from Latin <em>ternarius<\/em>) is an adjective meaning <em>&#8220;composed of three items&#8221;<\/em>. (<a href=\"https:\/\/en.wikipedia.org\/wiki\/Ternary\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/en.wikipedia.org\/wiki\/Ternary\">source<\/a>) So, literally, the <a href=\"https:\/\/blog.finxter.com\/python-one-line-ternary\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line Ternary\">ternary operator in Python<\/a> is composed of three operands.<\/p>\n<p><strong>Syntax<\/strong>: The three operands are written in an intuitive combination <code>... if ... else ...<\/code>.<\/p>\n<pre class=\"wp-block-preformatted\">&lt;On True&gt; if &lt;Condition&gt; else &lt;On False&gt;<\/pre>\n<figure class=\"wp-block-table is-style-stripes\">\n<table>\n<thead>\n<tr>\n<th>Operand<\/th>\n<th>Description<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>&lt;On True&gt;<\/td>\n<td>The return expression of the operator in case the condition evaluates to <code>True<\/code><\/td>\n<\/tr>\n<tr>\n<td>&lt;Condition&gt;<\/td>\n<td>The condition that determines whether to return the &lt;On True&gt; or the &lt;On False&gt; branch.<\/td>\n<\/tr>\n<tr>\n<td>&lt;On False&gt;<\/td>\n<td>The return expression of the operator in case the condition evaluates to <code>False<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table><figcaption><em>Operands of the Ternary Operator<\/em><\/figcaption><\/figure>\n<p>Let&#8217;s have a look at a minimum example in our interactive code shell:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/42f3df6ddd\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen=\"\" width=\"100%\" height=\"356\" frameborder=\"0\"><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Run the code and input your age. What&#8217;s the output? Run the code again and try to change the output!<\/em><\/p>\n<h2>Python One Line Two For Loops<\/h2>\n<h2>Python One Line True False<\/h2>\n<h2>Python One Line Too Long<\/h2>\n<h2>Python One Line Two Commands<\/h2>\n<h2>Python One Line To Multiple Line<\/h2>\n<h2>Python One Line URL Decode<\/h2>\n<h2>Python One Line Or<\/h2>\n<h2>Python One Line Object<\/h2>\n<h2>Python One Line Open File<\/h2>\n<h2>Python One Line Print<\/h2>\n<h2>Python One Line Print For Loop<\/h2>\n<h2>Python One Line Print If<\/h2>\n<h2>Python One Line Print List<\/h2>\n<h2>Python One Line Parse JSON<\/h2>\n<h2>Python One Line Pretty Print JSON<\/h2>\n<h2>Python One Line Array Filter<\/h2>\n<h2>Python One Line Append<\/h2>\n<h2>Python One Line And Or<\/h2>\n<h2>Python One Line Conditional Assignment<\/h2>\n<h2>Python One Swap<\/h2>\n<h2>Python One Line Sum<\/h2>\n<h2>Python One Line Sort<\/h2>\n<h2>Python One Line Semicolon<\/h2>\n<h2>Python One Line Dictionary<\/h2>\n<h2>Python One Line Function Definition<\/h2>\n<h2>Python One Line Def<\/h2>\n<h2>Python One Line Docstring<\/h2>\n<h2>Python One Line Dict Comprehension<\/h2>\n<h2>Python One Line Double For Loop<\/h2>\n<h2>Python One Line Download File<\/h2>\n<h2>Python One Line For Loop Append<\/h2>\n<h2>Python One Line Generator<\/h2>\n<h2>Python One Line FizzBuzz<\/h2>\n<h2>Python One Line HTTP Get<\/h2>\n<h2>Python Global in One Line<\/h2>\n<h2>Python One Line Hello World<\/h2>\n<h2>Python One Line Comment<\/h2>\n<h2>Python One Line Class<\/h2>\n<h2>Python Define Two Variables in One Line<\/h2>\n<h2>Python Define Multiple Variables in One Line<\/h2>\n<h2>Python One Line If (Not) None<\/h2>\n<h2>Python One Line Map<\/h2><\/p>\n","protected":false},"excerpt":{"rendered":"<p>This is a running document in which I&#8217;ll answer all questions regarding the single line of Python code. If you want to check out my book &#8220;Python One-Liners&#8221; and become a one-liner wizard&#8212;be my guest! Let&#8217;s get started! Python One Line If Without Else Python One Line If Else Python One Line Elif Python One [&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-115311","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\/115311","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=115311"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/115311\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=115311"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=115311"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=115311"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}