Create an account


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

#1
Python One Line For Loop Lambda

<div><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>
<div class="wp-block-image is-style-default">
<figure class="aligncenter size-large is-resized"><img 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/uplo...00x187.png 300w, https://blog.finxter.com/wp-content/uplo...68x479.png 768w, https://blog.finxter.com/wp-content/uplo...150x94.png 150w" sizes="(max-width: 725px) 100vw, 725px" /></figure>
</div>
<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>—while adding <code>+1</code> to each value. Here’s your multi-liner:</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="">a = [1, 2, 3, 4]
b = []
for x in a: b.append(x+1)
print(b)
# [2, 3, 4, 5]</pre>
<p>How do you accomplish this in a single line of code?</p>
<p><strong>Answer</strong>: No, you don’t need a lambda function. What you’re looking for is a feature called <a href="https://blog.finxter.com/list-comprehension/" title="List Comprehension in Python — A Helpful Illustrated Guide" target="_blank" rel="noreferrer noopener">list comprehension</a>. Here’s the one-liner expression that accomplishes this without the lambda function:</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="">b = [x+1 for x in a]
print(b)
# [2, 3, 4, 5]</pre>
<p>You can try this example yourself in our interactive code shell:</p>
<p> <iframe src="https://trinket.io/embed/python/642f8f083b" width="100%" height="400" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p>Let’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’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’ll also add another section about lambda functions. Finally, you’ll also learn about a third alternative method to solve this exact problem by using the lambda function in combination with Python’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>
<p>So, stay with me—you’ll become a better coder in the process! <img src="https://s.w.org/images/core/emoji/12.0.0-1/72x72/1f642.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h2>List Comprehension 101</h2>
<p>List comprehension is a compact way of creating lists. The simple formula is <code>[expression + context]</code>.</p>
<ul>
<li><strong>Expression: </strong>What to do with each list element?</li>
<li><strong>Context: </strong>What elements to select? The context consists of an arbitrary number of <code>for</code> and <code>if</code> statements.</li>
</ul>
<p>The example <code>[x for x in range(3)]</code> creates the list <code>[0, 1, 2]</code>.</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="A Simple Introduction to List Comprehension in Python" width="1400" height="788" src="https://www.youtube.com/embed/9qsq2Vf48W8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p>Have a look at the following interactive code snippet—can you figure out what’s printed to the shell? Go ahead and click “Run” to see what happens in the code:</p>
<p> <iframe src="https://trinket.io/embed/python/139fa01035" marginwidth="0" marginheight="0" allowfullscreen="" width="100%" height="356" frameborder="0"></iframe> </p>
<p>I’ll explain both ways of generating a new list in the following.</p>
<p><strong>Example</strong>: Say you want to <a href="https://blog.finxter.com/how-to-filter-a-list-of-lists-in-python/" target="_blank" rel="noreferrer noopener">filter out all customers</a> from your database who earn more than $1,000,000. This is what a newbie not knowing list comprehension would do:</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=""># (name, $-income)
customers = [("John", 240000), ("Alice", 120000), ("Ann", 1100000), ("Zach", 44000)] # your high-value customers earning &lt;$1M
whales = []
for customer, income in customers: if income>1000000: whales.append(customer)
print(whales)
# ['Ann']</pre>
<p>This snippet needs four lines just to create a <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener">list </a>of high-value customers (whales)!</p>
<p>Instead, a much better way of doing the same thing is to use list comprehension:</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="">whales = [x for x,y in customers if y>1000000]
print(whales)
# ['Ann']</pre>
<p>List comprehension is dead simple when you know the formula.</p>
<blockquote class="wp-block-quote">
<p>“A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.”</p>
<p><cite><a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions">Official Python Documentation<br /></a></cite></p></blockquote>
<p>Here is the formula for list comprehension. That’s the one thing you should take home from this tutorial. </p>
<p><strong>Formula: List comprehension consists of two parts. </strong></p>
<p><strong>‘[‘ + expression + context + ‘]’</strong></p>
<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img src="https://blog.finxter.com/wp-content/uploads/2020/05/listcomp-1024x576.jpg" alt="List Comprehension" class="wp-image-8559" width="768" height="432" srcset="https://blog.finxter.com/wp-content/uploads/2020/05/listcomp-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w" sizes="(max-width: 768px) 100vw, 768px" /></figure>
</div>
<p><strong>The first part is the expression.</strong> In the example above it was the variable <code>x</code>. But you can also use a more complex expression such as <code>x.upper()</code>. Use any variable in your expression that you have defined in the context within a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-one-line-for-loop-a-simple-tutorial/" target="_blank">loop statement</a>. See this example:</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="">whales = [x.upper() for x,y in customers if y>1000000]
print(whales)
# ['ANN']</pre>
<p><strong>The second part is the context</strong>. The context consists of an arbitrary number of <a href="https://blog.finxter.com/if-then-else-in-one-line-python/" target="_blank" rel="noreferrer noopener">for and if clauses</a>. The single goal of the context is to define (or restrict) the sequence of elements on which we want to apply the expression. That’s why you sometimes see complex restrictions such as this:</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="">small_fishes = [x + str(y) for x,y in customers if y&lt;1000000 if x!='John']
# (John is not a small fish...)
print(small_fishes)
# ['Alice120000', 'Zach44000']</pre>
<p>Albrecht, one of the loyal readers of my <a href="https://blog.finxter.com/subscribe/" target="_blank" rel="noreferrer noopener">“Coffee Break Python”</a> email course, pointed out that you can break the formula further down using the following blueprint:</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="">lst = [&lt;expression> for &lt;item> in &lt;collection> if &lt;expression>] </pre>
<p><a href="https://blog.finxter.com/list-comprehension/" target="_blank" rel="noreferrer noopener" title="List Comprehension in Python — A Helpful Illustrated Guide">A detailed tutorial on the topic is available for free at this tutorial on the Finxter blog. </a></p>
<h2>Lambda Function 101</h2>
<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>
<p>Here’s a practical example where lambda functions are used to generate an incrementor function:</p>
<p> <iframe src="https://trinket.io/embed/python/e83f61f8d7" marginwidth="0" marginheight="0" allowfullscreen="" width="100%" height="356" frameborder="0"></iframe> </p>
<p><em><strong>Exercise</strong>: Add another parameter to the lambda function!</em></p>
<p>Watch the video or read the article to learn about lambda functions in Python:</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="Let's Play Finxter - The Lambda Function in Python" width="1400" height="788" src="https://www.youtube.com/embed/kBg4n52XoUQ?start=20&feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p><strong>Puzzle</strong>. Here’s a small code puzzle to test your skills:</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 make_incrementor(n): return lambda x: x + n
f = make_incrementor(42)
print(f(0))
print(f(1))</pre>
<p>To test your understanding, you can solve this exact code puzzle with the topic “lambda functions in Python” at my <a href="https://app.finxter.com/learn/computer/science/370">Finxter code puzzle app</a>.</p>
<p><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">Find the detailed article on lambda functions here. </a></p>
<h2>Alternative Method 3: map() + lambda + list()</h2>
<p>Interestingly, there’s a third way of solving the above problem by using the <code><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()</a></code> function (and the lambda function):</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=""># Method 3: map() + lambda + list()
a = [1, 2, 3, 4]
b = list(map(lambda x: x+1, a))
print(b)
# [2, 3, 4, 5]</pre>
<p>You can learn about the <code>map()</code> function in my video tutorial here:</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="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>
</div>
</figure>
<p>However, it would be better if you <a href="https://blog.finxter.com/how-to-get-rid-of-pythons-map-function-with-list-comprehension/" target="_blank" rel="noreferrer noopener" title="How to Get Rid of Python’s Map Function With List Comprehension">avoided the map function</a>—it’s not readable and <a href="https://blog.finxter.com/which-is-faster-list-comprehension-or-map-function-in-python/" target="_blank" rel="noreferrer noopener" title="Which is Faster: List Comprehension or Map Function in Python?">less efficient</a> than list comprehension. </p>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
</div>


https://www.sickgaming.net/blog/2020/07/...op-lambda/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016