Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python One Line Function Definition

#1
Python One Line Function Definition

<div><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>
<p><strong>Problem</strong>: How to define a function in a single line of Python code?</p>
<p><strong>Example</strong>: Say, you’ve got the following function in three lines. How to compress them into a single line of Python code?</p>
<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']
say_hi(*friends)
</pre>
<p>The code defines a function <code>say_hi</code> that takes an iterable as input—the names of your friends—and prints <code>'hi x'</code> for each element <code>x</code> in your iterable. </p>
<p>The output is:</p>
<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 Alice
hi Bob
hi Ann '''</pre>
<p>Let’s dive into the different methods to accomplish this! First, here’s a quick interactive overview to test the waters:</p>
<p> <iframe 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>
<p><em><strong>Exercise</strong>: Run the code—is the output the same for all four methods?</em></p>
<p>Next, you’ll learn about each method in greater detail!</p>
<h2>Method 1: Lambda Function</h2>
<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>
<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>
<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
hi = lambda lst: [print('hi', x) for x in lst]</pre>
<p>In the example, you want to print a string for each element in an iterable—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>
<p>You obtain the following output:</p>
<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) '''
hi Alice
hi Bob
hi Ann '''</pre>
<h2>Method 2: Function Definition</h2>
<p>A similar idea is employed in this one-liner example—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>
<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
def hi(lst): [print('hi', x) for x in lst]</pre>
<p>The output is the same as before:</p>
<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) '''
hi Alice
hi Bob
hi Ann '''</pre>
<p>This approach is more Pythonic than the first one because there’s no throw-away return value and it’s more concise. </p>
<h2>Method 3: exec()</h2>
<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>
<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>
<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>
<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()
exec("def hi(*lst):\n for x in lst:\n print('hi', x)\nhi(*friends)")</pre>
<p>If you run the code, you’ll see the same output as before:</p>
<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) '''
hi Alice
hi Bob
hi Ann '''</pre>
<p>This is very hard to read—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>
<p>Watch the video if you want to learn more details about this technique:</p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="[Don'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>
</div>
</figure>
<h2>Python One-Liners Book</h2>
<p><strong>Python programmers will improve their computer science skills with these useful one-liners.</strong></p>
<figure class="wp-block-image size-medium is-resized"><a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noopener noreferrer"><img 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/uplo...00x277.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x708.jpg 768w" sizes="(max-width: 512px) 100vw, 512px" /></a></figure>
<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 “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.</p>
<p>The book’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’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:</p>
<p><strong>•</strong>&nbsp;&nbsp;Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution<br /><strong>•</strong>&nbsp;&nbsp;Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics<br /><strong>•</strong>&nbsp;&nbsp;Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning<br /><strong>•</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>•</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>
<p>By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.</p>
<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>
</div>


https://www.sickgaming.net/blog/2020/09/...efinition/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016