{"id":18026,"date":"2022-02-22T09:26:11","date_gmt":"2022-02-22T09:26:11","guid":{"rendered":"https:\/\/machinelearningplus.com\/?p=18026"},"modified":"2023-01-29T08:32:26","modified_gmt":"2023-01-29T08:32:26","slug":"generators-in-python","status":"publish","type":"post","link":"https:\/\/machinelearningplus.com\/python\/generators-in-python\/","title":{"rendered":"Generators in Python &#8211; How to lazily return values only when needed and save memory?"},"content":{"rendered":"<p>Generators in python provide an efficient way of generating numbers or objects as and when needed, without having to store all the values in memory beforehand.<\/p>\n<h2>Introduction<\/h2>\n<p>You can think of Generators as a simple way of creating <a href=\"python\/iterators-in-python-iterables-vs-iterators\/\">iterators<\/a> without having to create a class with <code>__iter__()<\/code> and <code>__next__()<\/code> methods.<\/p>\n<p>So <strong>how to create a Generator?<\/strong><\/p>\n<p>There are multiple ways, but the most common way to declare a function with a <code>yield<\/code> instead of a <code>return<\/code> statement. This way you will be able to iterate it through a for-loop.<\/p>\n<pre><code class=\"language-python\"># Define a Generator function: squares.\ndef squares(numbers):\n  for i in numbers:\n    yield i*i\n<\/code><\/pre>\n<p>Create the generator and iterate.<\/p>\n<pre><code class=\"language-python\"># Create generator and iterate\nsq_gen = squares([1,2,3,4])\nfor i in sq_gen:\n  print(i)\n<\/code><\/pre>\n<p>#&gt; 1<br \/>\n#&gt; 4<br \/>\n#&gt; 9<br \/>\n#&gt; 16<\/p>\n<h2>Generator Basics: The advantage of using Generators<\/h2>\n<p>Now let&#8217;s get into the details of a generator. But first let&#8217;s understand some basics.<\/p>\n<p>Consider the following two approaches of printing the squares of values from 0 to 4:<\/p>\n<p><strong>Approach 1: Using list<\/strong><\/p>\n<pre><code class=\"language-python\"># Approach 1: Using list\nL = [0, 1, 2, 3, 4]\nfor i in L:\n  print(i*i)\n<\/code><\/pre>\n<p>#&gt; 0<br \/>\n#&gt; 1<br \/>\n#&gt; 4<br \/>\n#&gt; 9<br \/>\n#&gt; 16<\/p>\n<p><strong>Approach 2: Using range generator<\/strong><\/p>\n<pre><code class=\"language-python\"># Approach 2: Using range\nfor i in range(5):\n  print(i*i)\n<\/code><\/pre>\n<p>#&gt; 0<br \/>\n#&gt; 1<br \/>\n#&gt; 4<br \/>\n#&gt; 9<br \/>\n#&gt; 16<\/p>\n<p>The first approach uses a list whereas the second one uses <code>range<\/code>, which is a generator. Though, the output is the same from both methods, you can notice the difference when the number of objects you want to iterate massively increases.<\/p>\n<p>Because, the list object occupies actual space in memory. As the size of the list increases, say you want to iterate till 5000, the required system memory increases proportionately.<\/p>\n<p>However, that is not the case with the generator <code>range<\/code>. <strong>No matter the number if iterations, the size of the generator itself does not change.<\/strong> That&#8217;s something!<\/p>\n<pre><code class=\"language-python\"># Check size of List vs Generator.\nimport sys\nprint(sys.getsizeof(L))\nprint(sys.getsizeof(range(6)))\n<\/code><\/pre>\n<p>#&gt; 120<br \/>\n#&gt; 48<\/p>\n<p>However, since <code>range<\/code> is a generator, the memory requirement of <code>range<\/code> for iterating 5000 numbers does not increase. Because, the values are generated only when needed and not actually stored.<\/p>\n<pre><code class=\"language-python\"># check size of a larger range\nprint(sys.getsizeof(range(5000)))\n<\/code><\/pre>\n<p>#&gt; 48<\/p>\n<p>That&#8217;s still the same number of bytes as <code>range(6)<\/code>.<\/p>\n<p><a href=\"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2022\/02\/Python_size_of_Objects_in_Bytes-min.png\"><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter size-large wp-image-18029\" src=\"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2022\/02\/Python_size_of_Objects_in_Bytes-min-1024x529.png\" alt=\"Python size of objects\" width=\"1024\" height=\"529\" srcset=\"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2022\/02\/Python_size_of_Objects_in_Bytes-min-1024x529.png 1024w, https:\/\/machinelearningplus.com\/wp-content\/uploads\/2022\/02\/Python_size_of_Objects_in_Bytes-min-300x155.png 300w, https:\/\/machinelearningplus.com\/wp-content\/uploads\/2022\/02\/Python_size_of_Objects_in_Bytes-min-768x397.png 768w, https:\/\/machinelearningplus.com\/wp-content\/uploads\/2022\/02\/Python_size_of_Objects_in_Bytes-min.png 1105w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/a><\/p>\n<p>Source: GeeksforGeeks<\/p>\n<p>Now, that&#8217;s the advantage of using generators.<\/p>\n<p>The good part is, Python allows you to create your own generator as per your custom logic. There are multiple ways to do it though. Let&#8217;s see some examples.<\/p>\n<h2>Approach 1. Using the yield keyword<\/h2>\n<p>We have already seen this. Let&#8217;s create the same logic of creating squares of numbers using the <code>yield<\/code> keyword and this time, we define it using a function.<\/p>\n<ol>\n<li>Define the generator function<\/li>\n<\/ol>\n<pre><code class=\"language-python\">def squares(numbers):\n  for i in numbers:\n    yield i*i\n<\/code><\/pre>\n<ol>\n<li>Create the generator object<\/li>\n<\/ol>\n<pre><code class=\"language-python\">nums_gen = squares([1,2,3,4])\nnums_gen\n<\/code><\/pre>\n<p>#&gt;<\/p>\n<p>Notice, <strong>it has only created a generator object and not the values we desire<\/strong>. Yet. To actually generate the values, you need to iterate and get it out.<\/p>\n<pre><code class=\"language-python\">print(next(nums_gen))\nprint(next(nums_gen))\nprint(next(nums_gen))\nprint(next(nums_gen))\n<\/code><\/pre>\n<p>#&gt; 1<br \/>\n#&gt; 4<br \/>\n#&gt; 9<br \/>\n#&gt; 16<\/p>\n<p><strong>What does <code>yield<\/code> do?<\/strong><\/p>\n<p>The yield statement is basically responsible for creating the generator that can be iterated upon.<\/p>\n<p>Now, what happens when you use <code>Yield<\/code>?<\/p>\n<p>Two things mainly:<\/p>\n<ol>\n<li>Because you&#8217;ve used the <code>yield<\/code> statement in the func definition, a dunder <code>__next__()<\/code> method has automatically been added to the <code>nums_gen<\/code>, making it an iterable. So, now you can call <code>next(nums_gen)<\/code>.<\/p>\n<\/li>\n<li>\n<p>Once you call <code>next(nums_gen)<\/code>, it starts executing the logic defined in <code>squares()<\/code>, until it hits upon the <code>yield<\/code> keyword. Then, it sends the yielded value and pauses the function temporarily in that state without exiting. When the function is invoked the next time, the state at which it was last paused is remembered and execution is continued from that point onwards. This continues until the generator is exhausted.<\/p>\n<\/li>\n<\/ol>\n<p>The magic in this process is, <strong>all the local variables that you had created within the function&#8217;s local name space will be available in the next iteration, that is when <code>next<\/code> is called again explicitly or when iterating in a for loop.<\/strong><\/p>\n<p>Had we used the <code>return<\/code> instead, the function would have exited, killing off all the variables in it&#8217;s local namespace.<\/p>\n<p><strong><code>yield<\/code> basically makes the function to remember its \u2018state\u2019.<\/strong> This function can be used to generate values as per a custom logic, fundamentally become a &#8216;generator&#8217;.<\/p>\n<p><strong>What happens after exhausting all the values?<\/strong><\/p>\n<p>Once the values have been exhausted, a <code>StopIteration<\/code> error gets raised. You need to create the generator again in order to use it again to generate the values.<\/p>\n<pre><code class=\"language-python\"># Once exhausted it raises StopIteration error\nprint(next(nums_gen))\n<\/code><\/pre>\n<p>You will need to re-create it and run it again.<\/p>\n<pre><code class=\"language-python\">nums_gen = squares([1,2,3,4])\n<\/code><\/pre>\n<p>This time, let&#8217;s iterate with a for-loop.<\/p>\n<pre><code class=\"language-python\">for i in nums_gen:\n  print(i)\n<\/code><\/pre>\n<p>#&gt; 1<br \/>\n#&gt; 4<br \/>\n#&gt; 9<br \/>\n#&gt; 16<\/p>\n<p>Good.<\/p>\n<p>Alternately, you can make the generator keep generating endlessly without exhaustion. This can be done by creating it as a class that defines an <code>__iter__()<\/code> method with an <code>yield<\/code> statement.<\/p>\n<h2>Approach 2. Create using class as an iterable<\/h2>\n<pre><code class=\"language-python\"># Approach 3: Convert it to an class that implements a `__iter__()` method.\nclass Iterable(object):\n  def __init__(self, numbers):\n    self.numbers = numbers\n\n  def __iter__(self):\n    n = self.numbers\n    for i in range(n):\n      yield i*i\n\niterable = Iterable(4)\n\nfor i in iterable: # iterator created here\n  print(i)\n<\/code><\/pre>\n<p>#> 0<br \/>\n#> 1<br \/>\n#> 4<br \/>\n#> 9<\/p>\n<p>It&#8217;s fully iterated now.<\/p>\n<p>Run gain without re-creating iterable.<\/p>\n<pre><code class=\"language-python\">for i in iterable: # iterator again created here\n  print(i)\n<\/code><\/pre>\n<p>#> 0<br \/>\n#> 1<br \/>\n#> 4<br \/>\n#> 9<\/p>\n<h2>Approach 3. Creating generator without using yield<\/h2>\n<pre><code class=\"language-python\">gen = (i*i for i in range(5))\ngen\n<\/code><\/pre>\n<p>#> at 0x000002372CA82E40><\/p>\n<pre><code class=\"language-python\">for i in gen:\n  print(i)\n<\/code><\/pre>\n<p>#> 0<br \/>\n#> 1<br \/>\n#> 4<br \/>\n#> 9<br \/>\n#> 16<\/p>\n<p>Try again, it can be re-used.<\/p>\n<pre><code class=\"language-python\">for i in gen:\n  print(i)\n<\/code><\/pre>\n<p>This example seems redundant because it can be easily done using <code>range<\/code>.<\/p>\n<p>Let&#8217;s see another example of reading a text file. Let&#8217;s split the sentences into a list of words.<\/p>\n<pre><code class=\"language-python\">gen = (i.split() for i in open(\"textfile.txt\", \"r\", encoding=\"utf8\"))\ngen\n<\/code><\/pre>\n<p>#&gt; at 0x000002372CA84190&gt;<\/p>\n<p>Create generator again<\/p>\n<pre><code class=\"language-python\">for i in gen:\n  print(i)\n<\/code><\/pre>\n<pre><code class=\"language-python\">OUTPUT\n#&gt; ['Amid', 'controversy', 'over', '\u2018motivated\u2019', 'arrest', 'in', 'sand', 'mining', 'case,']\n#&gt; ['Punjab', 'Congress', 'chief', 'Navjot', 'Singh', 'Sidhu', 'calls', 'for', '\u2018honest', 'CM', 'candidate\u2019.']\n#&gt; ['Amid', 'the', 'intense', 'campaign', 'for', 'the', 'Assembly', 'election', 'in', 'Punjab,']\n#&gt; ['due', 'less', 'than', 'three', 'weeks', 'from', 'now', 'on', 'February', '20,', 'the', 'Enforcement', 'Directorate', '(ED)']\n#&gt; ['on', 'Friday', 'arrested', 'Bhupinder', 'Singh', '\u2018Honey\u2019,', 'Punjab', 'Chief', 'Minister']\n#&gt; ['Charanjit', 'Singh', 'Channi\u2019s', 'nephew,', 'in', 'connection', 'with', 'an', 'illegal', 'sand', 'mining', 'case.']\n<\/code><\/pre>\n<p>Let&#8217;s try that again, but just <strong>extract the first 3 words in each line<\/strong>.<\/p>\n<pre><code class=\"language-python\">gen = (i.split()[:3] for i in open(\"textfile.txt\", \"r\", encoding=\"utf8\"))\nfor i in gen:\n  print(i)\n<\/code><\/pre>\n<pre><code class=\"language-python\">OUTPUT\n#&gt; ['Amid', 'controversy', 'over']\n#&gt; ['Punjab', 'Congress', 'chief']\n#&gt; ['Amid', 'the', 'intense']\n#&gt; ['due', 'less', 'than']\n#&gt; ['on', 'Friday', 'arrested']\n#&gt; ['Charanjit', 'Singh', 'Channi\u2019s']\n<\/code><\/pre>\n<p>Nice. We have covered all aspects of working with generators. Hope the concept of generators is clear now.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Generators in python provide an efficient way of generating numbers or objects as and when needed, without having to store all the values in memory beforehand. Introduction You can think of Generators as a simple way of creating iterators without having to create a class with __iter__() and __next__() methods. So how to create a [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":18003,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"site-sidebar-layout":"default","site-content-layout":"default","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"default","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[21],"tags":[1990,22],"class_list":["post-18026","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-generators","tag-python"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.0 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Generators in Python - How to lazily return values only when needed and save memory? - machinelearningplus<\/title>\n<meta name=\"description\" content=\"Generators in python provide an efficient way of generating numbers or objects as and when needed, without having to store all the values in memory beforehand.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/localhost:8080\/python\/generators-in-python\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Generators in Python - How to lazily return values only when needed and save memory? - machinelearningplus\" \/>\n<meta property=\"og:description\" content=\"Generators in python provide an efficient way of generating numbers or objects as and when needed, without having to store all the values in memory beforehand.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/localhost:8080\/python\/generators-in-python\/\" \/>\n<meta property=\"og:site_name\" content=\"machinelearningplus\" \/>\n<meta property=\"article:author\" content=\"https:\/\/www.facebook.com\/rtipaday\/\" \/>\n<meta property=\"article:published_time\" content=\"2022-02-22T09:26:11+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-01-29T08:32:26+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/localhost:8080\/wp-content\/uploads\/2022\/02\/Python-1.png\" \/>\n\t<meta property=\"og:image:width\" content=\"200\" \/>\n\t<meta property=\"og:image:height\" content=\"200\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Selva Prabhakaran\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/R_Programming\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Selva Prabhakaran\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"TechArticle\",\"@id\":\"https:\\\/\\\/localhost:8080\\\/python\\\/generators-in-python\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/localhost:8080\\\/python\\\/generators-in-python\\\/\"},\"author\":{\"name\":\"Selva Prabhakaran\",\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#\\\/schema\\\/person\\\/510885c0515804366fa644c38258391e\"},\"headline\":\"Generators in Python &#8211; How to lazily return values only when needed and save memory?\",\"datePublished\":\"2022-02-22T09:26:11+00:00\",\"dateModified\":\"2023-01-29T08:32:26+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/localhost:8080\\\/python\\\/generators-in-python\\\/\"},\"wordCount\":807,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/localhost:8080\\\/python\\\/generators-in-python\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/uploads\\\/2022\\\/02\\\/Python-1.png\",\"keywords\":[\"Generators\",\"Python\"],\"articleSection\":[\"Python\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/localhost:8080\\\/python\\\/generators-in-python\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/localhost:8080\\\/python\\\/generators-in-python\\\/\",\"url\":\"https:\\\/\\\/localhost:8080\\\/python\\\/generators-in-python\\\/\",\"name\":\"Generators in Python - How to lazily return values only when needed and save memory? - machinelearningplus\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/localhost:8080\\\/python\\\/generators-in-python\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/localhost:8080\\\/python\\\/generators-in-python\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/uploads\\\/2022\\\/02\\\/Python-1.png\",\"datePublished\":\"2022-02-22T09:26:11+00:00\",\"dateModified\":\"2023-01-29T08:32:26+00:00\",\"description\":\"Generators in python provide an efficient way of generating numbers or objects as and when needed, without having to store all the values in memory beforehand.\",\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/localhost:8080\\\/python\\\/generators-in-python\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/localhost:8080\\\/python\\\/generators-in-python\\\/#primaryimage\",\"url\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/uploads\\\/2022\\\/02\\\/Python-1.png\",\"contentUrl\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/uploads\\\/2022\\\/02\\\/Python-1.png\",\"width\":200,\"height\":200,\"caption\":\"Python\"},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#website\",\"url\":\"https:\\\/\\\/machinelearningplus.com\\\/\",\"name\":\"machinelearningplus\",\"description\":\"Learn Data Science (AI \\\/ ML) Online\",\"publisher\":{\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/machinelearningplus.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#organization\",\"name\":\"machinelearningplus\",\"url\":\"https:\\\/\\\/machinelearningplus.com\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/uploads\\\/2022\\\/05\\\/MachineLearningplus-logo.svg\",\"contentUrl\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/uploads\\\/2022\\\/05\\\/MachineLearningplus-logo.svg\",\"width\":348,\"height\":36,\"caption\":\"machinelearningplus\"},\"image\":{\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#\\\/schema\\\/logo\\\/image\\\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#\\\/schema\\\/person\\\/510885c0515804366fa644c38258391e\",\"name\":\"Selva Prabhakaran\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/litespeed\\\/avatar\\\/a994280177da541405c016f593e86ea7.jpg?ver=1783622267\",\"url\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/litespeed\\\/avatar\\\/a994280177da541405c016f593e86ea7.jpg?ver=1783622267\",\"contentUrl\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/litespeed\\\/avatar\\\/a994280177da541405c016f593e86ea7.jpg?ver=1783622267\",\"caption\":\"Selva Prabhakaran\"},\"description\":\"Selva is an experienced Data Scientist and leader, specializing in executing AI projects for large companies. Selva started machinelearningplus to make Data Science \\\/ ML \\\/ AI accessible to everyone. The website enjoys 4 Million+ readership. His courses, lessons, and videos are loved by hundreds of thousands of students and practitioners.\",\"sameAs\":[\"https:\\\/\\\/localhost:8080\\\/\",\"https:\\\/\\\/www.facebook.com\\\/rtipaday\\\/\",\"https:\\\/\\\/x.com\\\/https:\\\/\\\/twitter.com\\\/R_Programming\"],\"url\":\"https:\\\/\\\/machinelearningplus.com\\\/author\\\/selva86\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Generators in Python - How to lazily return values only when needed and save memory? - machinelearningplus","description":"Generators in python provide an efficient way of generating numbers or objects as and when needed, without having to store all the values in memory beforehand.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/localhost:8080\/python\/generators-in-python\/","og_locale":"en_US","og_type":"article","og_title":"Generators in Python - How to lazily return values only when needed and save memory? - machinelearningplus","og_description":"Generators in python provide an efficient way of generating numbers or objects as and when needed, without having to store all the values in memory beforehand.","og_url":"https:\/\/localhost:8080\/python\/generators-in-python\/","og_site_name":"machinelearningplus","article_author":"https:\/\/www.facebook.com\/rtipaday\/","article_published_time":"2022-02-22T09:26:11+00:00","article_modified_time":"2023-01-29T08:32:26+00:00","og_image":[{"width":200,"height":200,"url":"https:\/\/localhost:8080\/wp-content\/uploads\/2022\/02\/Python-1.png","type":"image\/png"}],"author":"Selva Prabhakaran","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/R_Programming","twitter_misc":{"Written by":"Selva Prabhakaran","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"TechArticle","@id":"https:\/\/localhost:8080\/python\/generators-in-python\/#article","isPartOf":{"@id":"https:\/\/localhost:8080\/python\/generators-in-python\/"},"author":{"name":"Selva Prabhakaran","@id":"https:\/\/machinelearningplus.com\/#\/schema\/person\/510885c0515804366fa644c38258391e"},"headline":"Generators in Python &#8211; How to lazily return values only when needed and save memory?","datePublished":"2022-02-22T09:26:11+00:00","dateModified":"2023-01-29T08:32:26+00:00","mainEntityOfPage":{"@id":"https:\/\/localhost:8080\/python\/generators-in-python\/"},"wordCount":807,"commentCount":0,"publisher":{"@id":"https:\/\/machinelearningplus.com\/#organization"},"image":{"@id":"https:\/\/localhost:8080\/python\/generators-in-python\/#primaryimage"},"thumbnailUrl":"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2022\/02\/Python-1.png","keywords":["Generators","Python"],"articleSection":["Python"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/localhost:8080\/python\/generators-in-python\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/localhost:8080\/python\/generators-in-python\/","url":"https:\/\/localhost:8080\/python\/generators-in-python\/","name":"Generators in Python - How to lazily return values only when needed and save memory? - machinelearningplus","isPartOf":{"@id":"https:\/\/machinelearningplus.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/localhost:8080\/python\/generators-in-python\/#primaryimage"},"image":{"@id":"https:\/\/localhost:8080\/python\/generators-in-python\/#primaryimage"},"thumbnailUrl":"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2022\/02\/Python-1.png","datePublished":"2022-02-22T09:26:11+00:00","dateModified":"2023-01-29T08:32:26+00:00","description":"Generators in python provide an efficient way of generating numbers or objects as and when needed, without having to store all the values in memory beforehand.","inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/localhost:8080\/python\/generators-in-python\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/localhost:8080\/python\/generators-in-python\/#primaryimage","url":"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2022\/02\/Python-1.png","contentUrl":"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2022\/02\/Python-1.png","width":200,"height":200,"caption":"Python"},{"@type":"WebSite","@id":"https:\/\/machinelearningplus.com\/#website","url":"https:\/\/machinelearningplus.com\/","name":"machinelearningplus","description":"Learn Data Science (AI \/ ML) Online","publisher":{"@id":"https:\/\/machinelearningplus.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/machinelearningplus.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/machinelearningplus.com\/#organization","name":"machinelearningplus","url":"https:\/\/machinelearningplus.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/machinelearningplus.com\/#\/schema\/logo\/image\/","url":"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2022\/05\/MachineLearningplus-logo.svg","contentUrl":"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2022\/05\/MachineLearningplus-logo.svg","width":348,"height":36,"caption":"machinelearningplus"},"image":{"@id":"https:\/\/machinelearningplus.com\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/machinelearningplus.com\/#\/schema\/person\/510885c0515804366fa644c38258391e","name":"Selva Prabhakaran","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/machinelearningplus.com\/wp-content\/litespeed\/avatar\/a994280177da541405c016f593e86ea7.jpg?ver=1783622267","url":"https:\/\/machinelearningplus.com\/wp-content\/litespeed\/avatar\/a994280177da541405c016f593e86ea7.jpg?ver=1783622267","contentUrl":"https:\/\/machinelearningplus.com\/wp-content\/litespeed\/avatar\/a994280177da541405c016f593e86ea7.jpg?ver=1783622267","caption":"Selva Prabhakaran"},"description":"Selva is an experienced Data Scientist and leader, specializing in executing AI projects for large companies. Selva started machinelearningplus to make Data Science \/ ML \/ AI accessible to everyone. The website enjoys 4 Million+ readership. His courses, lessons, and videos are loved by hundreds of thousands of students and practitioners.","sameAs":["https:\/\/localhost:8080\/","https:\/\/www.facebook.com\/rtipaday\/","https:\/\/x.com\/https:\/\/twitter.com\/R_Programming"],"url":"https:\/\/machinelearningplus.com\/author\/selva86\/"}]}},"_links":{"self":[{"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/posts\/18026","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/comments?post=18026"}],"version-history":[{"count":0,"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/posts\/18026\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/media\/18003"}],"wp:attachment":[{"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/media?parent=18026"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/categories?post=18026"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/tags?post=18026"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}