{"id":117575,"date":"2020-09-05T07:51:18","date_gmt":"2020-09-05T07:51:18","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=12724"},"modified":"2020-09-05T07:51:18","modified_gmt":"2020-09-05T07:51:18","slug":"python-one-line-function-definition","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/09\/05\/python-one-line-function-definition\/","title":{"rendered":"Python One Line Function Definition"},"content":{"rendered":"<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>Next, you&#8217;ll learn about each method in greater detail!<\/p>\n<h2>Method 1: Lambda Function<\/h2>\n<p>You can use a simple <a href=\"https:\/\/blog.finxter.com\/a-simple-introduction-of-the-lambda-function-in-python\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Lambda Functions in Python: A Simple Introduction\">lambda function<\/a> to accomplish this. <\/p>\n<p><strong>A lambda function is an anonymous function in Python.<\/strong> 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, z: x+y+z<\/code> would calculate the sum of the three argument values <code>x+y+z<\/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=\"\">friends = ['Alice', 'Bob', 'Ann'] # Method 1: Lambda Function\nhi = lambda lst: [print('hi', x) for x in lst]<\/pre>\n<p>In the example, you want to print a string for each element in an iterable&#8212;but the lambda function only returns an object. Thus, we return a dummy object: a list of <code><a href=\"https:\/\/blog.finxter.com\/python-cheat-sheet\/\" title=\"Python Beginner Cheat Sheet: 19 Keywords Every Coder Must Know\" target=\"_blank\" rel=\"noreferrer noopener\">None<\/a><\/code> objects. The only purpose of creating this list is to execute the print() function repeatedly, for each element in the <code>friends<\/code> list. <\/p>\n<p>You obtain 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(friends) '''\nhi Alice\nhi Bob\nhi Ann '''<\/pre>\n<h2>Method 2: Function Definition<\/h2>\n<p>A similar idea is employed in this one-liner example&#8212;but instead of using a lambda function, we define a regular function and simply skip the newline. This is possible if the function body has only one expression:<\/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=\"\">friends = ['Alice', 'Bob', 'Ann'] # Method 2: Function Definition\ndef hi(lst): [print('hi', x) for x in lst]<\/pre>\n<p>The output is the same as before:<\/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(friends) '''\nhi Alice\nhi Bob\nhi Ann '''<\/pre>\n<p>This approach is more Pythonic than the first one because there&#8217;s no throw-away return value and it&#8217;s more concise. <\/p>\n<h2>Method 3: exec()<\/h2>\n<p>The third method uses the <code>exec()<\/code> function. This is the brute-force approach to <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?\">one-linerize any multi-liner<\/a>!<\/p>\n<p>To make a Python one-liner out of any multi-line Python script, replace the new lines with a new line character <code>'\\n'<\/code> and pass the result into the <code>exec(...)<\/code> function. You can run this script from the outside (command line, shell, terminal) by using the command <code>python -c \"exec(...)\"<\/code>.<\/p>\n<p>We can apply this technique to the first example code snippet (the multi-line function definition) and rename the variables to make it more concise:<\/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=\"\">friends = ['Alice', 'Bob', 'Ann'] # Method 3: exec()\nexec(\"def hi(*lst):\\n for x in lst:\\n print('hi', x)\\nhi(*friends)\")<\/pre>\n<p>If you run the code, you&#8217;ll see the same output as before:<\/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(friends) '''\nhi Alice\nhi Bob\nhi Ann '''<\/pre>\n<p>This is very hard to read&#8212;our brain cannot grasp the whitespaces and newline characters easily. But I still wanted to include this method here because it shows how you or anyone else can compress complicated algorithms in a single line of Python code!<\/p>\n<p>Watch the video if you want to learn more details about this technique:<\/p>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" title=\"[Don&#039;t Do This At Home] How To One-Linerize Every Multi-Line Python Script &amp; Run It From The Shell\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/zGJgctQEkSU?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<h2>Python One-Liners Book<\/h2>\n<p><strong>Python programmers will improve their computer science skills with these useful one-liners.<\/strong><\/p>\n<figure class=\"wp-block-image size-medium is-resized\"><a href=\"https:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\" target=\"_blank\" rel=\"noopener noreferrer\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-1024x944.jpg\" alt=\"Python One-Liners\" class=\"wp-image-10007\" width=\"512\" height=\"472\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-300x277.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-768x708.jpg 768w\" sizes=\"auto, (max-width: 512px) 100vw, 512px\" \/><\/a><\/figure>\n<p><a href=\"https:\/\/amzn.to\/2WAYeJE\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/amzn.to\/2WAYeJE\"><em>Python One-Liners<\/em> <\/a>will teach you how to read and write &#8220;one-liners&#8221;: concise statements of useful functionality packed into a single line of code. You&#8217;ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.<\/p>\n<p>The book&#8217;s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You&#8217;ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You&#8217;ll also learn how to:<\/p>\n<p><strong>\u2022<\/strong>&nbsp;&nbsp;Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy\/nongreedy operators<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting<\/p>\n<p>By the end of the book, you&#8217;ll know how to write Python at its most refined, and create concise, beautiful pieces of &#8220;Python art&#8221; in merely a single line.<\/p>\n<p><strong><a href=\"https:\/\/amzn.to\/2WAYeJE\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/amzn.to\/2WAYeJE\"><em>Get your Python One-Liners Now!!<\/em><\/a><\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>A lambda function allows you to define a function in a single line. It starts with the keyword lambda, followed by a comma-separated list of zero or more arguments, followed by the colon and the return expression. For example, lambda x, y: x+y calculates the sum of the two argument values x+y in one line [&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-117575","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\/117575","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=117575"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/117575\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=117575"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=117575"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=117575"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}