{"id":201,"date":"2023-12-23T11:51:42","date_gmt":"2023-12-23T17:51:42","guid":{"rendered":"https:\/\/www.baizhao666.com\/?p=201"},"modified":"2024-07-17T18:46:05","modified_gmt":"2024-07-18T00:46:05","slug":"generator","status":"publish","type":"post","link":"https:\/\/www.baizhao666.com\/?p=201","title":{"rendered":"Generator"},"content":{"rendered":"\n<p>Generators in Python are essentially functions that using &#8220;yield&#8221; keyword instead of &#8220;return&#8221;. The trick is that &#8220;yield&#8221; does not end the function and a function can &#8220;yield&#8221; infinitely many things. The main down side is that we can&#8217;t simply call the generator to access all the output. Instead, we can iterate over the output inside a loop. The main advantage of a generator is the fact that its output is generated on demand. Normally, the variables that we defined need a place in memory to store it. Imagine a huge list contains millions of items inside, That requires a huge amount of memory to store and it will wake a long time to iterate it. But the output of a generator is not stored in memory by default, therefore, it would save tons of memory when dealing with large amounts of data.<\/p>\n\n\n\n<!--more-->\n\n\n\n<h3 class=\"wp-block-heading\">Create a generator<\/h3>\n\n\n\n<p>In Python, a generator works like a function. So we can simply use &#8220;def&#8221; to define a generator. Inside the function, we need to use &#8220;yield&#8221; instead of &#8220;return&#8221; to indicate the items that we want to yield. If the body of a def contains yield, the function automatically becomes a Python generator function. The syntax of a generator is:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>def generator_name():\n    yield statement<\/code><\/pre><\/div>\n\n\n\n<p>For example, if we want to yield the first positive 5 even integers. Instead of calling the generator directly to get the output, we need to iterate it.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code># define a generator\ndef my_gen():\n  for i in range(1, 6):\n    yield 2 * i\n\n# access the output\nfor i in my_gen():\n  print(i)<\/code><\/pre><\/div>\n\n\n\n<p>Output:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-plain\"><code>2\n4\n6\n8\n10<\/code><\/pre><\/div>\n\n\n\n<p>Instead of returning a specific value, the generator returns a iterable object. That means we can also iterate the generator using next() function.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code># define a generator\ndef my_gen():\n  for i in range(1, 6):\n    yield 2 * i\n\n# iterate using next()\ngen = my_gen()\nprint(next(gen))\nprint(next(gen))\nprint(next(gen))<\/code><\/pre><\/div>\n\n\n\n<p>Output:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-plain\"><code>2\n4\n6<\/code><\/pre><\/div>\n\n\n\n<p>When dealing with an extremely larger data set and trying to access it, the program might be interrupted by Python. However, we can make a generator which will generate the same numbers on demand. Since the numbers aren&#8217;t stored in memory, python doesn&#8217;t complain about the giant range being used.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code># an example of a list that is possibly too large to fit in memory\nL = [2*n for n in range(2**40)]\n\n# using generator\ndef my_gen():\n    for n in range(2**40):\n        yield 2*n<\/code><\/pre><\/div>\n\n\n\n<p>Generators can also be used for recursive sequences. For example, we can use generator to generate all Fibonacci Numbers. Compare with recursion, generator will be much faster.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code># a generator for all Fibonacci numbers\ndef fib_gen():\n    a0 = 1\n    a1 = 1\n    while True:\n        yield a0\n        a0, a1 = a1, a0+a1<\/code><\/pre><\/div>\n\n\n\n<p>We can actually turn any list comprehension into a generator, using parenthesis instead of square rackets.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code># list comprehension:\nL = [2*n for n in range(100)]\n\n# generator expression:\nG = (2*n for n in range(100))<\/code><\/pre><\/div>\n","protected":false},"excerpt":{"rendered":"<p>Generators in Python are essentially functions that using &#8220;yield&#8221; keyword instead of &#8220;return&#8221;. The trick is that &#8220;yield&#8221; does not end the function and a function can &#8220;yield&#8221; infinitely many things. The main down side is that we can&#8217;t simply call the generator to access all the output. Instead, we can iterate over the output &hellip; <\/p>\n<p class=\"link-more\"><a href=\"https:\/\/www.baizhao666.com\/?p=201\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;Generator&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4],"tags":[],"class_list":["post-201","post","type-post","status-publish","format-standard","hentry","category-python"],"_links":{"self":[{"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=\/wp\/v2\/posts\/201","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=201"}],"version-history":[{"count":2,"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=\/wp\/v2\/posts\/201\/revisions"}],"predecessor-version":[{"id":276,"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=\/wp\/v2\/posts\/201\/revisions\/276"}],"wp:attachment":[{"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=201"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=201"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=201"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}