{"id":115771,"date":"2020-07-23T06:56:49","date_gmt":"2020-07-23T06:56:49","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=11312"},"modified":"2020-07-23T06:56:49","modified_gmt":"2020-07-23T06:56:49","slug":"python-one-line-for-loop-lambda","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/07\/23\/python-one-line-for-loop-lambda\/","title":{"rendered":"Python One Line For Loop Lambda"},"content":{"rendered":"<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 loading=\"lazy\" decoding=\"async\" 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>You can try this example yourself in our interactive code shell:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/642f8f083b\" width=\"100%\" height=\"400\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen><\/iframe> <\/p>\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\/12.0.0-1\/72x72\/1f642.png\" alt=\"\ud83d\ude42\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><\/p>\n<h2>List Comprehension 101<\/h2>\n<p>List comprehension is a compact way of creating lists. The simple formula is <code>[expression + context]<\/code>.<\/p>\n<ul>\n<li><strong>Expression: <\/strong>What to do with each list element?<\/li>\n<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>\n<\/ul>\n<p>The example <code>[x for x in range(3)]<\/code> creates the list <code>[0, 1, 2]<\/code>.<\/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=\"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>\n<\/div>\n<\/figure>\n<p>Have a look at the following interactive code snippet&#8212;can you figure out what&#8217;s printed to the shell? Go ahead and click &#8220;Run&#8221; to see what happens in the code:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/139fa01035\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen=\"\" width=\"100%\" height=\"356\" frameborder=\"0\"><\/iframe> <\/p>\n<p>I&#8217;ll explain both ways of generating a new list in the following.<\/p>\n<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>\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=\"\"># (name, $-income)\ncustomers = [(\"John\", 240000), (\"Alice\", 120000), (\"Ann\", 1100000), (\"Zach\", 44000)] # your high-value customers earning &lt;$1M\nwhales = []\nfor customer, income in customers: if income>1000000: whales.append(customer)\nprint(whales)\n# ['Ann']<\/pre>\n<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>\n<p>Instead, a much better way of doing the same thing is to use list comprehension:<\/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=\"\">whales = [x for x,y in customers if y>1000000]\nprint(whales)\n# ['Ann']<\/pre>\n<p>List comprehension is dead simple when you know the formula.<\/p>\n<blockquote class=\"wp-block-quote\">\n<p>&#8220;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.&#8221;<\/p>\n<p><cite><a href=\"https:\/\/docs.python.org\/3\/tutorial\/datastructures.html#list-comprehensions\">Official Python Documentation<br \/><\/a><\/cite><\/p><\/blockquote>\n<p>Here is the formula for list comprehension. That&#8217;s the one thing you should take home from this tutorial. <\/p>\n<p><strong>Formula: List comprehension consists of two parts. <\/strong><\/p>\n<p><strong>&#8216;[&#8216; + expression + context + &#8216;]&#8217;<\/strong><\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" 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\/uploads\/2020\/05\/listcomp-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/05\/listcomp-768x432.jpg 768w\" sizes=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/figure>\n<\/div>\n<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>\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=\"\">whales = [x.upper() for x,y in customers if y>1000000]\nprint(whales)\n# ['ANN']<\/pre>\n<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&#8217;s why you sometimes see complex restrictions such as 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=\"\">small_fishes = [x + str(y) for x,y in customers if y&lt;1000000 if x!='John']\n# (John is not a small fish...)\nprint(small_fishes)\n# ['Alice120000', 'Zach44000']<\/pre>\n<p>Albrecht, one of the loyal readers of my <a href=\"https:\/\/blog.finxter.com\/subscribe\/\" target=\"_blank\" rel=\"noreferrer noopener\">&#8220;Coffee Break Python&#8221;<\/a> email course, pointed out that you can break the formula further down using the following blueprint:<\/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=\"\">lst = [&lt;expression> for &lt;item> in &lt;collection> if &lt;expression>] <\/pre>\n<p><a href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"List Comprehension in Python \u2014 A Helpful Illustrated Guide\">A detailed tutorial on the topic is available for free at this tutorial on the Finxter blog. <\/a><\/p>\n<h2>Lambda Function 101<\/h2>\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<p>Here&#8217;s a practical example where lambda functions are used to generate an incrementor function:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/e83f61f8d7\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen=\"\" width=\"100%\" height=\"356\" frameborder=\"0\"><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Add another parameter to the lambda function!<\/em><\/p>\n<p>Watch the video or read the article to learn about lambda functions in Python:<\/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=\"Let&#039;s Play Finxter - The Lambda Function in Python\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/kBg4n52XoUQ?start=20&#038;feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<p><strong>Puzzle<\/strong>. Here&#8217;s a small code puzzle to test your skills:<\/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 make_incrementor(n): return lambda x: x + n\nf = make_incrementor(42)\nprint(f(0))\nprint(f(1))<\/pre>\n<p>To test your understanding, you can solve this exact code puzzle with the topic &#8220;lambda functions in Python&#8221; at my <a href=\"https:\/\/app.finxter.com\/learn\/computer\/science\/370\">Finxter code puzzle app<\/a>.<\/p>\n<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>\n<h2>Alternative Method 3: map() + lambda + list()<\/h2>\n<p>Interestingly, there&#8217;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>\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: map() + lambda + list()\na = [1, 2, 3, 4]\nb = list(map(lambda x: x+1, a))\nprint(b)\n# [2, 3, 4, 5]<\/pre>\n<p>You can learn about the <code>map()<\/code> function in my video tutorial here:<\/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=\"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>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\u2019s Map Function With List Comprehension\">avoided the map function<\/a>&#8212;it&#8217;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>\n<h2>Where to Go From Here?<\/h2>\n<p>Enough theory, let\u2019s get some practice!<\/p>\n<p>To become successful in coding, you need to get out there and solve real problems for real people. That\u2019s how you can become a six-figure earner easily. And that\u2019s how you polish the skills you really need in practice. After all, what\u2019s the use of learning theory that nobody ever needs?<\/p>\n<p><strong>Practice projects is how you sharpen your saw in coding!<\/strong><\/p>\n<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>\n<p>Then become a Python freelance developer! It\u2019s the best way of approaching the task of improving your Python skills\u2014even if you are a complete beginner.<\/p>\n<p>Join my free webinar <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\">\u201cHow to Build Your High-Income Skill Python\u201d<\/a> and watch how I grew my coding business online and how you can, too\u2014from the comfort of your own home.<\/p>\n<p><a href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Join the free webinar now!<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Problem: 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 lambda function? Example: Given an array a = [1, 2, 3, 4]. You need to create a second [&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-115771","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\/115771","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=115771"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/115771\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=115771"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=115771"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=115771"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}