{"id":115652,"date":"2020-07-20T10:42:37","date_gmt":"2020-07-20T10:42:37","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=11110"},"modified":"2020-07-20T10:42:37","modified_gmt":"2020-07-20T10:42:37","slug":"python-one-line-for-loop-with-if","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/07\/20\/python-one-line-for-loop-with-if\/","title":{"rendered":"Python One Line For Loop With If"},"content":{"rendered":"<p>This tutorial will teach you how to write <strong>one-line for loops<\/strong> in Python using the popular expert feature of <em><strong>list comprehension<\/strong><\/em>. After you&#8217;ve learned the basics of list comprehension, you&#8217;ll learn how to restrict list comprehensions so that you can write custom filters quickly and effectively.<\/p>\n<p>Are you ready? Let&#8217;s roll up your sleeves and learn about list comprehension in Python!<\/p>\n<h2>List Comprehension Basics<\/h2>\n<p>The following section is based on my detailed article <a href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" title=\"List Comprehension in Python \u2014 A Helpful Illustrated Guide\" target=\"_blank\" rel=\"noreferrer noopener\"><strong><em>List Comprehension [Ultimate Guide]<\/em><\/strong><\/a>. Read the shorter version here or the longer version on the website&#8212;you decide!<\/p>\n<p>This overview graphic shows how to use list comprehension statement to create Python lists programmatically:<\/p>\n<figure class=\"wp-block-image is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/05\/listcomp-1024x576.jpg\" alt=\"List Comprehension\" width=\"768\" height=\"432\"\/><\/figure>\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><em><strong>Exercise<\/strong>: Run the code snippet and compare your guessed result with the actual one. Were you correct?<\/em><\/p>\n<p>Now, that you know about the basics of list comprehension (expression + context!), let&#8217;s dive into a more advanced example where list comprehension is used for filtering by adding an if clause to the context part.<\/p>\n<h2>List Comprehension for Filtering (using If Clauses)<\/h2>\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=\"How to Filter a List in Python?\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/3nG4TLkqzf8?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<p>You can also modify the list comprehension statement by restricting the context with another if statement:<\/p>\n<p><strong>Problem<\/strong>: Say, we want to create a list of squared numbers&#8212;but you only consider even and ignore odd numbers. <\/p>\n<p><strong>Example<\/strong>: The multi-liner way would be the following.<\/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=\"\">squares = [] for i in range(10): if i%2==0: squares.append(i**2) print(squares)\n# [0, 4, 16, 36, 64]\n<\/pre>\n<p>You create an empty list <code>squares<\/code> and successively add another square number starting from 0**2 and ending in 8**2&#8212;but only considering the even numbers 0, 2, 4, 6, 8. Thus, the result is the list <code>[0, 4, 16, 36, 64]<\/code>. <\/p>\n<p>Again, you can use list comprehension <code>[i**2 for i in range(10) <strong>if i%2==0<\/strong>]<\/code> with a restrictive if clause (in bold) in the context part to compress this in 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=\"\">print([i**2 for i in range(10) if i%2==0])\n# [0, 4, 16, 36, 64]<\/pre>\n<p>This line accomplishes the same output with much less bits.<\/p>\n<p><strong>Related Article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/define-a-function-in-one-line\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python One Line For Loop<\/a><\/p>\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<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>This tutorial will teach you how to write one-line for loops in Python using the popular expert feature of list comprehension. After you&#8217;ve learned the basics of list comprehension, you&#8217;ll learn how to restrict list comprehensions so that you can write custom filters quickly and effectively. Are you ready? Let&#8217;s roll up your sleeves and [&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-115652","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\/115652","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=115652"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/115652\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=115652"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=115652"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=115652"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}