{"id":75862,"date":"2020-01-30T11:35:07","date_gmt":"2020-01-30T06:05:07","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=75862"},"modified":"2020-01-30T11:35:07","modified_gmt":"2020-01-30T06:05:07","slug":"python-generators","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/python-generators\/","title":{"rendered":"Python Generators &#8211; A complete guide to create and use generators"},"content":{"rendered":"<p>In our <strong>Python Iterators <\/strong>article, we create our own <strong>iterators<\/strong>.<\/p>\n<p><strong>Generators<\/strong> are also used to <strong>create functions<\/strong> that <strong>behave<\/strong> like <strong>iterators<\/strong>. It is a different <strong>approach<\/strong> to <strong>create iterators<\/strong>.<\/p>\n<p>People often misunderstood this topic as a hard one because it looks <strong>different<\/strong> than the usual one but in fact, it is very <strong>easy<\/strong>. This article will teach you about <strong>Python generators<\/strong>, how you can <strong>create<\/strong> and <strong>effectively use generators<\/strong> in your <strong>code<\/strong>.<\/p>\n<p>We will also see its <strong>applications<\/strong> so let\u2019s get started.<\/p>\n<p>&nbsp;<\/p>\n<h3>What are Python Generator Functions?<\/h3>\n<p><strong>Generator functions<\/strong> are special kind of functions that <strong>returns<\/strong> an <strong>iterator<\/strong> and we can<strong> loop<\/strong> it through just like a <strong>list<\/strong>, to <strong>access<\/strong> the <strong>objects<\/strong> one at a <strong>time<\/strong>.<\/p>\n<p>Python generator functions are a <strong>simple<\/strong> way to <strong>create iterators<\/strong>. They solve the common problem of <strong>creating iterable<\/strong> <strong>objects<\/strong>. The traditional way was to <strong>create a class<\/strong> and then we have to <strong>implement __iter__()<\/strong> and<strong> __next__()<\/strong> methods.<\/p>\n<p>We also have to manage the <strong>internal state<\/strong> and <strong>raise<\/strong> the <strong>StopIteration<\/strong> <strong>exception<\/strong> when the <strong>generator ends<\/strong>.<\/p>\n<h3>How to Create a Python Generator?<\/h3>\n<p>A <strong>Python generator<\/strong> is <strong>created<\/strong> like a <strong>normal function<\/strong> but we <strong>do not use<\/strong> the <strong>return statement<\/strong> in <strong>generators<\/strong>.<\/p>\n<p>For generating a value, we use the <strong>yield keyword<\/strong>. When we use the <strong>yield keyword<\/strong> inside a function, it <strong>automatically<\/strong> becomes a <strong>generator function<\/strong>.<\/p>\n<p>Let us understand the working of a generator with a <strong>simple generator<\/strong>.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">def mygen():\n    yield 10\n    yield 20\n    yield 40\nf\ngen = mygen()\n\nprint(next(gen))\nprint(next(gen))\nprint(next(gen))\nprint(next(gen))<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">10<br \/>\n20<br \/>\n40<br \/>\nTraceback (most recent call last):<br \/>\n<span style=\"font-weight: 400\">\u00a0\u00a0<\/span>File\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 &#8220;C:\/Users\/Techvidvan\/AppData\/Local\/Programs\/Python\/Python38-32\/test.py&#8221;, line 11, in &lt;module&gt;<br \/>\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0<\/span>print(next(gen))<br \/>\nStopIteration<\/div>\n<p>Here, the<strong> mygen()<\/strong> function is a <strong>generator function<\/strong> in which we used<strong> 3 yield statements<\/strong>.<\/p>\n<p>The <strong>next()<\/strong> function used on the <strong>generator<\/strong> object <strong>returns<\/strong> the <strong>value<\/strong> of the <strong>first yield statement<\/strong>. Again calling the <strong>next()<\/strong> will then return the <strong>value<\/strong> from the <strong>second function<\/strong> and so on. When it gets <strong>exhausted<\/strong> the <strong>generator<\/strong> function <strong>raises<\/strong> the <strong>StopIteration exception<\/strong>.<\/p>\n<p>We can also use the <strong>for loop<\/strong> for easy <strong>traversing<\/strong> the <strong>elements<\/strong>.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">def mygen():\n    n = 1\n    yield n\n    n+=2\n    yield n\n    n+=3\n    yield n\n    yield \"End\"\n\nfor n in mygen():\n    print(n)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">1<br \/>\n3<br \/>\n6<br \/>\nEnd<\/div>\n<p>One thing to notice here is that when the <strong>generator yields<\/strong> the values it remembers the <strong>value<\/strong> of the <strong>variable<\/strong> n <strong>between<\/strong> each call.<\/p>\n<h3>Python Generators with Loops<\/h3>\n<p>The above examples were simple, only for understanding the <strong>working<\/strong> of the <strong>generators<\/strong>. Now we will see <strong>generators<\/strong> with a <strong>loop<\/strong> that is more <strong>practically applicable<\/strong> for <strong>creating <\/strong>customized <strong>iterable objects<\/strong>. We can use<strong> for-loop<\/strong> to <strong>yield values<\/strong>.<\/p>\n<p>Let us generate a <strong>sequence<\/strong> of <strong>Fibonacci numbers<\/strong>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">def fib_sequence(n):\n   a,b = 0,1\n   for i in range(n):\n       yield a\n       a,b = b,a+b\n\nfor i in fib_sequence(10):\n    print(i)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">0<br \/>\n1<br \/>\n1<br \/>\n2<br \/>\n3<br \/>\n5<br \/>\n8<br \/>\n13<br \/>\n21<br \/>\n34<\/div>\n<h3>Using Generators with List() Function<\/h3>\n<p>We can use the<strong> lits() function<\/strong> to <strong>yield<\/strong> all the <strong>values<\/strong> into a <strong>list<\/strong>. This is very <strong>handy<\/strong> sometimes. We can try this by using the same<strong> fib_sequence()<\/strong> <strong>generator function<\/strong> we made.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">print( list(fib_sequence(20)) )<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]<\/div>\n<h3>Python Generator Expressions<\/h3>\n<p>If you are familiar with <strong>list <\/strong><strong>comprehensions<\/strong> then this would be very easy for you to understand. We have even a more <strong>shorthand technique<\/strong> to <strong>create python generators<\/strong>.<\/p>\n<p>In <strong>list comprehensions<\/strong> we use <strong>[] brackets<\/strong> while in <strong>generator expressions<\/strong> we use <strong>() parenthesis<\/strong>. They are used at places where we quickly want to use a <strong>generator<\/strong> right away.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">gen = (x**2 for x in range(10))\n\nfor x in gen:\n  print(x)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">0<br \/>\n1<br \/>\n4<br \/>\n9<br \/>\n16<br \/>\n25<br \/>\n36<br \/>\n49<br \/>\n64<br \/>\n81<\/div>\n<p>Here, we created a generator that is used to <strong>generate<\/strong> a <strong>square<\/strong> of <strong>0-9 numbers<\/strong>. If we <strong>print<\/strong> the <strong>gen object<\/strong> then we see that it is a <strong>generator object<\/strong>.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">print(gen)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">&lt;generator object &lt;genexpr&gt; at 0x05F3F7D0&gt;<\/div>\n<h3>Why Generators are Used?<\/h3>\n<ul>\n<li>Generators are used to <strong>create iterable<\/strong> <strong>objects<\/strong>.<\/li>\n<li>They are easier to implement than the <strong>creation <\/strong>of <strong>iterable objects<\/strong> which we saw in the iterables article.<\/li>\n<li>The generators <strong>yield<\/strong> <strong>one value<\/strong> at a time from a <strong>set of items<\/strong>.<\/li>\n<li>So they are <strong>memory efficient<\/strong> as they require <strong>less space<\/strong> and we don\u2019t have to store everything at once.<\/li>\n<li>It is also easier to <strong>implement<\/strong> an <strong>infinite generation<\/strong> of <strong>series<\/strong>.<\/li>\n<li>We cannot store <strong>infinite series<\/strong> of a sequence in <strong>memory<\/strong> so with generators we can continuously <strong>generate values<\/strong> or <strong>infinite values(theoretically)<\/strong><\/li>\n<li>Generators are also helpful in <strong>reading<\/strong> and <strong>performing operations<\/strong> on <strong>large files<\/strong>.<\/li>\n<li>We can use <strong>generators<\/strong> to <strong>effectively<\/strong> write <strong>code<\/strong> for our <strong>programs<\/strong>.<\/li>\n<\/ul>\n<h3>Summary<\/h3>\n<p><strong>Python Generators<\/strong> are often <strong>misinterpreted<\/strong> as a hard topic but in fact, they are very useful and easy, once you start understanding how it works. We saw what Python generators are, <strong>how<\/strong> to <strong>create them<\/strong> and <strong>iterate over generators<\/strong> with <strong>for loops<\/strong>.<\/p>\n<p>Moreover, we saw an even more easy way to create generators i.e. <strong>generators expression<\/strong>.<\/p>\n<p>In the end, we saw the <strong>advantages<\/strong> of python generators.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In our Python Iterators article, we create our own iterators. Generators are also used to create functions that behave like iterators. It is a different approach to create iterators. People often misunderstood this topic&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":76044,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1053],"tags":[1508,1509,1510,1511,1512,1513],"class_list":["post-75862","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-generators-in-python","tag-how-to-create-a-python-generator","tag-python-generator-expressions","tag-python-generators","tag-python-generators-with-loops","tag-what-are-python-generator-functions"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Python Generators - A complete guide to create and use generators - TechVidvan<\/title>\n<meta name=\"description\" content=\"Learn to create generators in Python, its functions and expressions. Also, explore Python generators with loops and see why generators are used.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/python-generators\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Generators - A complete guide to create and use generators - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Learn to create generators in Python, its functions and expressions. Also, explore Python generators with loops and see why generators are used.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/python-generators\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2020-01-30T06:05:07+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/01\/python-generators.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"802\" \/>\n\t<meta property=\"og:image:height\" content=\"420\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python Generators - A complete guide to create and use generators - TechVidvan","description":"Learn to create generators in Python, its functions and expressions. Also, explore Python generators with loops and see why generators are used.","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:\/\/techvidvan.com\/tutorials\/python-generators\/","og_locale":"en_US","og_type":"article","og_title":"Python Generators - A complete guide to create and use generators - TechVidvan","og_description":"Learn to create generators in Python, its functions and expressions. Also, explore Python generators with loops and see why generators are used.","og_url":"https:\/\/techvidvan.com\/tutorials\/python-generators\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2020-01-30T06:05:07+00:00","og_image":[{"width":802,"height":420,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/01\/python-generators.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/python-generators\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-generators\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Python Generators &#8211; A complete guide to create and use generators","datePublished":"2020-01-30T06:05:07+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-generators\/"},"wordCount":745,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-generators\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/01\/python-generators.jpg","keywords":["generators in python","How to Create a Python Generator","python Generator expressions","python generators","Python Generators with Loops","What are Python Generator Functions"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/python-generators\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/python-generators\/","url":"https:\/\/techvidvan.com\/tutorials\/python-generators\/","name":"Python Generators - A complete guide to create and use generators - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-generators\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-generators\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/01\/python-generators.jpg","datePublished":"2020-01-30T06:05:07+00:00","description":"Learn to create generators in Python, its functions and expressions. Also, explore Python generators with loops and see why generators are used.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-generators\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/python-generators\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/python-generators\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/01\/python-generators.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/01\/python-generators.jpg","width":802,"height":420,"caption":"python generators tutorial"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/python-generators\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Python Generators &#8211; A complete guide to create and use generators"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/75862","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=75862"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/75862\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/76044"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=75862"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=75862"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=75862"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}