{"id":9532,"date":"2022-08-09T21:10:00","date_gmt":"2022-08-09T19:10:00","guid":{"rendered":"https:\/\/monodes.com\/predaelli\/?p=9532"},"modified":"2022-08-09T09:12:31","modified_gmt":"2022-08-09T07:12:31","slug":"7-python-one-liners-that-will-blow-your-mind","status":"publish","type":"post","link":"https:\/\/monodes.com\/predaelli\/2022\/08\/09\/7-python-one-liners-that-will-blow-your-mind\/","title":{"rendered":"7 Python One-Liners that will Blow Your Mind"},"content":{"rendered":"\n<p><a href=\"https:\/\/medium.com\/@xiaoxugao?source=post_page-----479d5b2ab93a--------------------------------\">Xiaoxu Gao<\/a> wrote <a href=\"https:\/\/towardsdatascience.com\/7-python-one-liners-that-will-blow-your-mind-479d5b2ab93a\">7 Python One-Liners that will Blow Your Mind<\/a><\/p>\n\n\n\n<!--nextpage-->\n\n\n\n<h2 class=\"wp-block-heading\" id=\"9aec\">Less is more?<\/h2>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/miro.medium.com\/max\/700\/0*HbkvisySyqYvQ66H\" alt=\"\"\/><figcaption>Photo by <a href=\"https:\/\/unsplash.com\/@photos_by_lanty\" rel=\"noreferrer noopener\" target=\"_blank\">Photos by Lanty<\/a> from <a href=\"https:\/\/unsplash.com\/\" rel=\"noreferrer noopener\" target=\"_blank\">Unsplash<\/a><\/figcaption><\/figure>\n\n\n\n<p id=\"8593\">The term <a href=\"https:\/\/en.wikipedia.org\/wiki\/One-line_joke\" rel=\"noreferrer noopener\" target=\"_blank\">one-liner<\/a> comes from comedy where a joke is delivered in a single line. A good one-liner is said to be meaningful and concise. This concept also exists in programming. Python one-liners are short programs that can perform powerful operations. It\u2019s nearly impossible in other languages like Java, so it\u2019s considered as a Pythonic feature.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"7abc\"><strong>Arguments about Python one-liners<\/strong><\/h2>\n\n\n\n<p id=\"0aef\">If it\u2019s your first time seeing one-liners, please remember Python one-liner is a double-edged sword. On one hand, it makes code <em>look cool<\/em> and it\u2019s definitely a way to impress your colleagues or interviewers. But on the other hand, a fancy one-liner can be confusing and difficult to understand and turn into a way to show off your skills. Thus, do expect some arguments during the code review. As a rule of thumb, one-liners are very welcomed in Python, but if it goes too far and starts to confuse people, then it\u2019s the moment to drop it. Eventually, your code needs to be readable and maintainable.<\/p>\n\n\n\n<p id=\"93fd\">Anyway, in this article, I want to give you some practical examples of Python one-liners that can boost your code quality. And I will also show you some fancy one-liners to have fun with. In any case, you must know all the possible ways of expressing your thoughts in code so that you can make the right decision.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"409a\">Swap two variables<\/h2>\n\n\n\n<pre class=\"wp-block-preformatted\"># normal<br \/>c = a<br \/>a = b<br \/>b = c# 1-liner<br \/>a,b = b,a<\/pre>\n\n\n\n<p id=\"691b\">In a normal situation, when you swap two variables, you need a middle-man in between. I also mentioned this trick in my <a rel=\"noreferrer noopener\" target=\"_blank\" href=\"https:\/\/towardsdatascience.com\/how-to-write-pythonic-code-208ec1513c49\">How to Write Pythonic Code article<\/a>. In Python, you can do it in one line. The right side is an expression that is actually a tuple (b,a) and the left side is variables that represent the first and second variable in the tuple.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"abca\">List comprehension<\/h2>\n\n\n\n<pre class=\"wp-block-preformatted\">result = []<br \/>for i in range(10):<br \/>    result.append(i**2)# use list comprehension<br \/>result = [i**2 for i in range(10)]<\/pre>\n\n\n\n<p id=\"2e32\">This is another Pythonic feature I put in <a rel=\"noreferrer noopener\" target=\"_blank\" href=\"https:\/\/towardsdatascience.com\/how-to-write-pythonic-code-208ec1513c49\">my previous article<\/a>. It tells Python what to do with each element in the list. The list contains both <code class=\"\" data-line=\"\">for<\/code> and <code class=\"\" data-line=\"\">if<\/code> statements. For example:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">#list comprehension with if<br \/>result = [i**2 for i in range(10) if i%2==0]#read file in one-line<br \/>[line.strip() for line in open(filename)]<\/pre>\n\n\n\n<p id=\"f2a6\">List\/Set comprehension is such a powerful tool that everyone must know it. It allows you to write code that\u2019s elegant and almost as easy to read as plain English. Each list comprehension includes 3 elements: 1) expression. Any valid expression like <code class=\"\" data-line=\"\">i**2<\/code> or <code class=\"\" data-line=\"\">line.strip()<\/code>. 2) member. The object in the iterable. 3) iterable. A list, set, generator, or any other iterable object.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"89ea\">Lambda and Map functions<\/h2>\n\n\n\n<p id=\"ce7f\">The next level of list comprehension is the lambda function. Check out <a rel=\"noreferrer noopener\" target=\"_blank\" href=\"https:\/\/towardsdatascience.com\/learn-python-lambda-from-scratch-f4a9c07e4b34\">Learn Python Lambda from Scratch<\/a>.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p>Unlike lambda forms in other languages, where they add functionality, Python lambdas are only a shorthand notation if you\u2019re too lazy to define a function.<\/p><\/blockquote>\n\n\n\n<pre class=\"wp-block-preformatted\"># traditional function with def<br \/>def sum(a, b):    <br \/>  return a + b# lambda function with name<br \/>sum_lambda = lambda x, y: x + y<\/pre>\n\n\n\n<p id=\"9033\">Lambda functions are normally combined with Python higher-order functions. There are a couple of built-in higher-order functions like <code class=\"\" data-line=\"\">map<\/code>, <code class=\"\" data-line=\"\">filter<\/code>, <code class=\"\" data-line=\"\">reduce<\/code>, <code class=\"\" data-line=\"\">sorted<\/code>, <code class=\"\" data-line=\"\">sum<\/code>, <code class=\"\" data-line=\"\">any<\/code>, <code class=\"\" data-line=\"\">all<\/code> .<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">map(lambda x:x**2, [i for i in range(3)]) <br \/># &lt;map object at 0x105558a90&gt;filter(lambda x: x % 2 == 0, [1, 2, 3])<br \/># &lt;filter object at 0x1056093d0&gt;from functools import reduce<br \/>reduce(lambda x, y: x + y, [1, 2, 3])<br \/># 6<\/pre>\n\n\n\n<p id=\"1629\">It is worth noting that the return of <code class=\"\" data-line=\"\">map<\/code> and <code class=\"\" data-line=\"\">filter<\/code> are objects, not the result of the function. If you want to get the actual result, you need to convert it to a list like <code class=\"\" data-line=\"\">list(map(lambda x:x**2, [i for i in range(3)])<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"9d64\">Print without newlines<\/h2>\n\n\n\n<p id=\"c781\"><code class=\"\" data-line=\"\">print<\/code> is one of the most basic statements in every programming language. But have you ever read the definition of <code class=\"\" data-line=\"\">print<\/code> interface in Python doc?<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>print<\/strong>(<em>*objects<\/em>, <em>sep=' '<\/em>, <em>end='\\n'<\/em>, <em>file=sys.stdout<\/em>, <em>flush=False<\/em>)<\/pre>\n\n\n\n<p id=\"34ff\">The function prints objects, separated by <code class=\"\" data-line=\"\">sep<\/code> and followed by <code class=\"\" data-line=\"\">end<\/code>. So let\u2019s look at this one-liner.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">#for-loop<br \/>for i in range(1,5):<br \/>    print(i, end=\" \")#one-liner<br \/>print(*range(1,5)) #1 2 3 4<\/pre>\n\n\n\n<p id=\"ff45\">Since <code class=\"\" data-line=\"\">print<\/code> accepts an iterable, we can directly use <code class=\"\" data-line=\"\">*range(1,5)<\/code> as the input and it has the same output as the for loop.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"db2c\">Walrus<\/h2>\n\n\n\n<p id=\"ccd0\">Walrus operator is a feature since Python 3.8. It gives you a new syntax <code class=\"\" data-line=\"\">:= <\/code>for assignment variables in the middle of expressions. It is to avoid calling the same function twice.<\/p>\n\n\n\n<p id=\"09da\">This is an example from Python doc. Instead of having a separate line to calculate <code class=\"\" data-line=\"\">mo<\/code> upfront, walrus operator allows you to calculate it on the flight.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># without walrus<br \/>discount = 0.0<br \/>mo = re.search(r'(\\d+)% discount', \"10% discount\")<br \/>if mo:<br \/>  discount = float(mo.group(1))\/100.0# with walrus<br \/>discount = 0.0<br \/>if (mo := re.search(r'(\\d+)% discount', \"10% discount\")):<br \/>  discount = float(mo.group(1)) \/ 100.0<\/pre>\n\n\n\n<p id=\"969d\">But I find walrus quite useful in the for\/while loop because the code looks really neat and just like normal English.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># without walrus<br \/>f = open(\"source\/a.txt\")<br \/>line = f.readline()<br \/>while line != '':<br \/>    print(line)<br \/>    line = f.readline()# with walrus<br \/>f = open(\"f.txt\")<br \/>while (line := f.readline()) != '':<br \/>    print(line)<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"389d\">Fibonacci<\/h2>\n\n\n\n<p id=\"5825\">Alright, now let\u2019s checkout some fancy examples. Do you know you can actually code Fibonacci algorithm in one line? It\u2019s pretty amazing!<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">#for-loop<br \/>def fib(x):<br \/>    if x &lt;= 2:<br \/>        return 1<br \/>    return fib(x - 1) + fib(x - 2)#1-liner<br \/>fib = lambda x: x if x&lt;=1 else fib(x-1) + fib(x-2)<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"45e6\">Quicksort<\/h2>\n\n\n\n<p id=\"77b3\">If you think you can still handle it, let\u2019s see the next level of one-liner. Here is the one-liner version of quick sort, a famous sorting algorithm.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">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 &gt; l[0]]) if l else []<br \/>q([])<\/pre>\n\n\n\n<p id=\"8619\">In my opinion, it\u2019s fun to look at it and understand how powerful Python is, but don\u2019t use it in your work. <strong>When one-liner gets too long to fit in one line, it\u2019s time to drop it.<\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"bc28\">Conclusion<\/h2>\n\n\n\n<p id=\"4e31\">As usual, I hope you find this article useful and learned a new way to improve your code quality. Feel free to share your experience with one-liners. Cheers!<\/p>\n","protected":false},"excerpt":{"rendered":"<p class=\"excerpt\">Xiaoxu Gao wrote 7 Python One-Liners that will Blow Your Mind<\/p>\n<p class=\"more-link-p\"><a class=\"more-link\" href=\"https:\/\/monodes.com\/predaelli\/2022\/08\/09\/7-python-one-liners-that-will-blow-your-mind\/\">Read more &rarr;<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"activitypub_content_warning":"","activitypub_content_visibility":"","activitypub_max_image_attachments":4,"activitypub_interaction_policy_quote":"anyone","activitypub_status":"","footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[113],"tags":[],"class_list":["post-9532","post","type-post","status-publish","format-standard","hentry","category-python"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p6daft-2tK","jetpack-related-posts":[{"id":8194,"url":"https:\/\/monodes.com\/predaelli\/2021\/02\/24\/python-packages-and-one-liners\/","url_meta":{"origin":9532,"position":0},"title":"Python Packages and one-liners","author":"Paolo Redaelli","date":"2021-02-24","format":false,"excerpt":"That Makes You Life Easier 20 Python Packages That You Must Try | by Abhay Parashar | Level Up Coding 25 Useful Python One-Liners That You Should know","rel":"","context":"In &quot;Documentations&quot;","block_context":{"text":"Documentations","link":"https:\/\/monodes.com\/predaelli\/category\/documentations\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":9674,"url":"https:\/\/monodes.com\/predaelli\/2022\/09\/28\/10-powerful-python-one-liners\/","url_meta":{"origin":9532,"position":1},"title":"10 Powerful Python One-Liners.","author":"Paolo Redaelli","date":"2022-09-28","format":false,"excerpt":"I shall Eiffellize those, one day or another: 10 Powerful Python One-Liners. Python one-liners can be just as\u2026 | by Ishaan Gupta | Sep, 2022 | Python in Plain English 10 Powerful Python One-Liners Python one-liners can be just as powerful as a long and tedious program written in another\u2026","rel":"","context":"In &quot;Agenda&quot;","block_context":{"text":"Agenda","link":"https:\/\/monodes.com\/predaelli\/category\/agenda\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/monodes.com\/predaelli\/wp-content\/uploads\/sites\/4\/2022\/09\/1jLSxNQvNqsYr02VB_wr96A.jpeg?resize=350%2C200&ssl=1","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/monodes.com\/predaelli\/wp-content\/uploads\/sites\/4\/2022\/09\/1jLSxNQvNqsYr02VB_wr96A.jpeg?resize=350%2C200&ssl=1 1x, https:\/\/i0.wp.com\/monodes.com\/predaelli\/wp-content\/uploads\/sites\/4\/2022\/09\/1jLSxNQvNqsYr02VB_wr96A.jpeg?resize=525%2C300&ssl=1 1.5x"},"classes":[]},{"id":9373,"url":"https:\/\/monodes.com\/predaelli\/2022\/05\/12\/one-liner-static-web-server\/","url_meta":{"origin":9532,"position":2},"title":"One liner, static web-server","author":"Paolo Redaelli","date":"2022-05-12","format":false,"excerpt":"willurd on web-servers.md show quite a few one-liner (or mostly) commands that will run an ad hoc http static server in your current (or specified) directory, available at http:\/\/localhost:8000. I think I will use only the Python 3.x version which is as simple as python -m http.server 8000","rel":"","context":"In &quot;Tricks&quot;","block_context":{"text":"Tricks","link":"https:\/\/monodes.com\/predaelli\/category\/documentations\/tricks\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":12976,"url":"https:\/\/monodes.com\/predaelli\/2025\/03\/15\/codon-high-performance-python-compiler\/","url_meta":{"origin":9532,"position":3},"title":"Codon: high-performance Python compiler","author":"Paolo Redaelli","date":"2025-03-15","format":false,"excerpt":"Codon: high-performance Python compiler Codon is a high-performance Python implementation that compiles to native machine code without any runtime overhead. Typical speedups over vanilla Python are on the order of 10-100x or more, on a single thread. Codon's performance is typically on par with (and sometimes better than) that of\u2026","rel":"","context":"In &quot;Python&quot;","block_context":{"text":"Python","link":"https:\/\/monodes.com\/predaelli\/category\/python\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":6318,"url":"https:\/\/monodes.com\/predaelli\/2019\/12\/15\/eiffels-conditional-expressions\/","url_meta":{"origin":9532,"position":4},"title":"Eiffel&#8217;s conditional expressions","author":"Paolo Redaelli","date":"2019-12-15","format":false,"excerpt":"The ternary conditional operator is a short-hand method for writing an if\/else statement. Does Python Have a Ternary Conditional Operator? Yes, it does. This remids me that Eiffel, at least \"ISE Eiffel\" does actually have conditional expressions that are the same: answer := if time < noon then \"Good morning\"\u2026","rel":"","context":"In &quot;Eiffel&quot;","block_context":{"text":"Eiffel","link":"https:\/\/monodes.com\/predaelli\/category\/eiffel\/"},"img":{"alt_text":"Jonathan Hsu","src":"https:\/\/i0.wp.com\/miro.medium.com\/fit\/c\/58\/58\/2%2A_KGzadiy9s83D4vzhsCyyg.png?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]},{"id":14807,"url":"https:\/\/monodes.com\/predaelli\/2026\/01\/23\/the-xonsh-shell-python-powered-shell\/","url_meta":{"origin":9532,"position":5},"title":"The Xonsh Shell \u2014 Python-powered shell","author":"Paolo Redaelli","date":"2026-01-23","format":false,"excerpt":"The Xonsh Shell \u2014 Python-powered shell. Python shell. Python in the shell. Shell in Python. Shell and Python. Python and shell.Xonsh (sounds like \"consh\") is a modern, full-featured and cross-platform python shell. The language is a superset of Python 3.6+ with additional shell primitives that you are used to from\u2026","rel":"","context":"In &quot;Python&quot;","block_context":{"text":"Python","link":"https:\/\/monodes.com\/predaelli\/category\/python\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/monodes.com\/predaelli\/wp-content\/uploads\/sites\/4\/2026\/01\/xonsh.webp?fit=257%2C399&ssl=1&resize=350%2C200","width":350,"height":200},"classes":[]}],"jetpack_likes_enabled":true,"_links":{"self":[{"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/posts\/9532","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/comments?post=9532"}],"version-history":[{"count":0,"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/posts\/9532\/revisions"}],"wp:attachment":[{"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/media?parent=9532"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/categories?post=9532"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/tags?post=9532"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}