{"id":118106,"date":"2020-09-17T07:51:03","date_gmt":"2020-09-17T07:51:03","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=13194"},"modified":"2020-09-17T07:51:03","modified_gmt":"2020-09-17T07:51:03","slug":"python-one-line-generator","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/09\/17\/python-one-line-generator\/","title":{"rendered":"Python One Line Generator"},"content":{"rendered":"<p><strong><em>A generator function is a Pythonic way to create an iterable without explicitly storing it in memory.<\/em><\/strong> This reduces memory usage of your code without incurring any additional costs.<\/p>\n<p>The following code shows a function <code>get_numbers(n)<\/code> that returns a <a href=\"https:\/\/blog.finxter.com\/python-lists\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"The Ultimate Guide to Python Lists\">list <\/a>of <code>n<\/code> <a href=\"https:\/\/blog.finxter.com\/python-random-module\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python\u2019s Random Module \u2013 Everything You Need to Know to Get Started\">random <\/a>numbers. <\/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=\"\">import random # NOT A GENERATOR!\n# Create and return a list of numbers\ndef get_numbers(n): numbers = [] for i in range(n): numbers.append(random.random()) # List of n elements exists in memory return numbers # Sum up 1000 random numbers\ns = 0\nfor x in get_numbers(1000): s += x\nprint(s)<\/pre>\n<p>However, this is not very efficient code because you create a list in advance without need. What if you had 1,000,000,000 numbers? Your memory would quickly fill up! <\/p>\n<p>A better way is to use a generator function with the <code>yield<\/code> keyword that creates the random numbers dynamically as they are iterated over:<\/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=\"\">import random # GENERATOR\n# Generate numbers one by one\ndef generate_numbers(n): for i in range(n): yield random.random() # Sum up 1000 random numbers\ns = 0\nfor x in generate_numbers(1000): s += x\nprint(s)<\/pre>\n<p>There are two big advantages to using a generator: <\/p>\n<ul>\n<li>(1) You don&#8217;t have to create a huge list first and store it in memory but generate the next element as you iterate over it. <\/li>\n<li>(2) It&#8217;s shorter and more concise. <\/li>\n<\/ul>\n<p>However, it may not be concise enough for you! <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/12.0.0-1\/72x72\/1f609.png\" alt=\"\ud83d\ude09\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> So, here&#8217;s the problem addressed in this article:<\/p>\n<hr class=\"wp-block-separator\"\/>\n<p><strong>Problem<\/strong>: Can we write a one-line generator?<\/p>\n<p>Let&#8217;s dive into different methods to accomplish this!<\/p>\n<h2>Method 1: One-Liner Generator Function<\/h2>\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(sum(random.random() for i in range(1000)))<\/pre>\n<p>The code consists of the following parts:<\/p>\n<ul>\n<li>The <code><a href=\"https:\/\/blog.finxter.com\/the-separator-and-end-arguments-of-the-python-print-function\/\" title=\"Python Print Function [And Its SECRET Separator &amp; End Arguments]\" target=\"_blank\" rel=\"noreferrer noopener\">print()<\/a><\/code> function prints the result of the expression to the shell. <\/li>\n<li>The <code><a href=\"https:\/\/blog.finxter.com\/python-one-line-sum-list\/\" title=\"Python One Line Sum List\" target=\"_blank\" rel=\"noreferrer noopener\">sum()<\/a><\/code> function sums over all values in the following iterable.<\/li>\n<li>The generator expression <code>random.random() for i in range(1000)<\/code> generates 1000 random numbers and feeds them into the outer sum() function without creating all of them at once.<\/li>\n<\/ul>\n<p>This way, we still don&#8217;t store the whole list of 1000 numbers in memory but create them dynamically. <\/p>\n<h2>Method 2: exec()<\/h2>\n<p>The following method is not pretty&#8212;but it solves the problem to create a generator in a single line of 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=\"\">exec('def g(n):\\n for i in range(n):\\n yield random.random()')\n<\/pre>\n<p>The <code><a href=\"https:\/\/blog.finxter.com\/how-to-execute-multiple-lines-in-a-single-line-python-from-command-line\/\" title=\"How to Execute Multiple Lines in a Single Line Python From Command-Line?\" target=\"_blank\" rel=\"noreferrer noopener\">exec()<\/a><\/code> function can be used to one-linerize every Python code snippet under the sun. Just pass the code you want to run as a string and replace all newlines with the newline character <code>'\\n'<\/code>. This way, you can create a generator function <code>g(n)<\/code> that dynamically creates <code>n<\/code> random numbers. You can now iterate them using the standard code snippet:<\/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=\"\">s = 0\nfor x in g(1000): s += x\nprint(s)\n# 488.318368852096<\/pre>\n<p>Because the numbers are random, the output will be different for you. You can try it yourself in our interactive shell:<\/p>\n<p> <iframe loading=\"lazy\" height=\"600px\" width=\"100%\" src=\"https:\/\/repl.it\/@finxter\/CriticalPinkBracket?lite=true\" scrolling=\"no\" frameborder=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\"><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: What&#8217;s the output for you? Why is it different than ours?<\/em><\/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","protected":false},"excerpt":{"rendered":"<p>A generator function is a Pythonic way to create an iterable without explicitly storing it in memory. This reduces memory usage of your code without incurring any additional costs. The following code shows a function get_numbers(n) that returns a list of n random numbers. import random # NOT A GENERATOR! # Create and return a [&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-118106","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\/118106","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=118106"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/118106\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=118106"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=118106"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=118106"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}