{"id":80181,"date":"2021-01-20T09:00:21","date_gmt":"2021-01-20T03:30:21","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=80181"},"modified":"2021-01-20T09:00:21","modified_gmt":"2021-01-20T03:30:21","slug":"python-generators-vs-iterators","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/python-generators-vs-iterators\/","title":{"rendered":"Difference between Iterator and Generator in Python"},"content":{"rendered":"<p>In this article, we\u2019ll mainly learn about the difference between iterator and generator in Python, but of course, we need to know them separately as well.<\/p>\n<p>Let&#8217;s start!!!!<\/p>\n<h2>What is Python Generators<\/h2>\n<p>A python generator\u2019s typical function lends coder a sequence of values to iterate on.<\/p>\n<p>The following is a general example of generators in python.<\/p>\n<p><strong>Python Generator Example<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">a=(1,2,3,4,5,6,7,8,9,10,11)\nfor i in range(1,10,2):\n    print(i)\n   \n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">1<br \/>\n3<br \/>\n5<br \/>\n7<br \/>\n9<\/div>\n<h3>Creating Generators in Python<\/h3>\n<p>It is quite simple to create a generator in Python in runtime. If a function contains an output statement then the generator needs to work as a library. Both yield and Return will return some value from a function from a particular code.<\/p>\n<p><strong>Python Generators with a Loop Example<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def thisistech(string):\n    tech = len(string)\n    for k in range(tech - 1, -1, -1):\n        yield string[k]\n\nfor char in thisistech(\"whassup\"):\n    print(char)\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">p<br \/>\nu<br \/>\ns<br \/>\ns<br \/>\na<br \/>\nh<br \/>\nw<\/div>\n<h3>Python Generator Expression<\/h3>\n<p>Simple python generator can be easily created by importing from the library directly.<\/p>\n<p><strong>Python generator Expression Example<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">myfirstlist = [1, 10,9,0]\n\nlistmy = [k**2 for k in myfirstlist]\n\ngenerator = (k**2 for k in myfirstlist)\n\nprint(listmy)\nprint(generator)\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">[1, 100,81,0]<\/div>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">mysecondlist = [1, 10]\n\np = (j**2 for j in mysecondlist)\nprint(next(p))\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">1<\/div>\n<p>Generator expressions can be used as function arguments in any code, as:<\/p>\n<p><strong>Syntax:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&gt;&gt;&gt; sum(w**2 for x in mysecondlist)\n<\/pre>\n<h3>Advantages of Python Generators<\/h3>\n<p><strong>1. Easy to Implement Anywhere<\/strong><br \/>\nThe python generators are easy to implement in the dynamic as well as user-defined codes. They generally fetch values from libraries, which make them accessible on every python version.<\/p>\n<p><strong>2. Highly Memory Efficient<\/strong><br \/>\nA normal function to return a sequence will create the entire sequence in memory before returning the result within the runtime itself.<\/p>\n<p><strong>3. Represent Infinite Stream<\/strong><br \/>\nGenerators can represent the length of a series of infinite numbers taken at a time. And this is supported by the library function.<\/p>\n<p><strong>4. Pipelining Generators in Python<\/strong><br \/>\nMultiple generators can be used to pipeline a series of operations within the runtime itself.<\/p>\n<h4>Advanced Generators<\/h4>\n<p>These generators work on the yielding property of the libraries. They are basically used in data and csv files.<\/p>\n<h2>Python Iterators<\/h2>\n<p>A Python iterator typically returns us an iterator object- one value at a time. An example of an iterator in python.<\/p>\n<p><strong>Example of Python iterators<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&gt;&gt;&gt; next(it)\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Traceback (most recent call last)<\/div>\n<h3>Iterables in Python<\/h3>\n<p>As the name suggests, the iterables are those defined objects which can iterate different values for a code.<\/p>\n<p>They are generally in the form of arrays.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">it[Symboloftheiterator] = function* () \n  yield 2;\n  yield 1;\n<\/pre>\n<h2>Comparison Between Python Generator and Iterator<\/h2>\n<table>\n<tbody>\n<tr>\n<td><b>S.no\u00a0<\/b><\/td>\n<td><b>Parameters<\/b><\/td>\n<td><b>Generator<\/b><\/td>\n<td><b>Iterator<\/b><\/td>\n<\/tr>\n<tr>\n<td><b>1<\/b><\/td>\n<td><b>Implementation\u00a0<\/b><\/td>\n<td><span style=\"font-weight: 400\">Implemented using a function defined in the runtime.<\/span><\/td>\n<td><span style=\"font-weight: 400\">Implemented using a class in the code.<\/span><\/td>\n<\/tr>\n<tr>\n<td><b>2<\/b><\/td>\n<td><b>Yield usage for coder<\/b><\/td>\n<td><span style=\"font-weight: 400\">Generator uses the \u2018yield\u2019 keyword<\/span><\/td>\n<td><span style=\"font-weight: 400\">Iterator does not use any keyword<\/span><\/td>\n<\/tr>\n<tr>\n<td><b>3<\/b><\/td>\n<td><b>Class variable<\/b><\/td>\n<td><span style=\"font-weight: 400\">Generator does not need a class in python.<\/span><\/td>\n<td><span style=\"font-weight: 400\">Iterator implements its own class<\/span><\/td>\n<\/tr>\n<tr>\n<td><b>4<\/b><\/td>\n<td><b>Globals and locals\u00a0<\/b><\/td>\n<td><span style=\"font-weight: 400\">Generator saves the states of the local variables<\/span><\/td>\n<td><span style=\"font-weight: 400\">Iterator also does not uses local variable<\/span><\/td>\n<\/tr>\n<tr>\n<td><b>5<\/b><\/td>\n<td><b>Yield usage for user<\/b><\/td>\n<td><span style=\"font-weight: 400\">Uses the yield keyword for the output.<\/span><\/td>\n<td><span style=\"font-weight: 400\">Does not use the yield keyword anywhere in the code.<\/span><\/td>\n<\/tr>\n<tr>\n<td><b>6<\/b><\/td>\n<td><b>Efficiency\u00a0<\/b><\/td>\n<td><span style=\"font-weight: 400\">Generators\u00a0 write fast and compact code<\/span><\/td>\n<td><span style=\"font-weight: 400\"> Iterator writes custom and long codes<\/span><\/td>\n<\/tr>\n<tr>\n<td><b>7<\/b><\/td>\n<td><b>Functions<\/b><\/td>\n<td><span style=\"font-weight: 400\"> Generator use python functions<\/span><\/td>\n<td><span style=\"font-weight: 400\">Iterator,use the iter() and next() functions<\/span><\/td>\n<\/tr>\n<tr>\n<td><b>8<\/b><\/td>\n<td><b>Storage capacity<\/b><\/td>\n<td><span style=\"font-weight: 400\">Generator is not memory efficient<\/span><\/td>\n<td><span style=\"font-weight: 400\">Iterator is memory-efficient<\/span><\/td>\n<\/tr>\n<tr>\n<td><b>9<\/b><\/td>\n<td><b>Relative working<\/b><\/td>\n<td><span style=\"font-weight: 400\">Usage results in a concise code in any\u00a0 relative function.<\/span><\/td>\n<td><span style=\"font-weight: 400\">Usage results in a relatively less concise code as compared in the whole python code.<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def thisisnew():\n#this defines new variable\nif i==1:\n   While i&gt;0:\n      Yield i\n i-=1\n#this executes only when first is not satisfied\nFor i in thisistech():\n    print(i)\nFor i in thisisnew():\n    print()\n\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">error<\/div>\n<p>A generator function class can be identified in a python code.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def thisisgen():\n    print(\"class is a generator\")\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">&gt;&gt;&gt; thisisgen()<br \/>\nclass is a generator<br \/>\n&gt;&gt;&gt;<\/div>\n<h3>Common Relationship Between Python Iterators and Generators<\/h3>\n<p>A python iterator and generator both fetch information from the predefined libraries. They help in the proper conduct of the code.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def thisistech():\n    print(\"this is true\")\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">&gt;&gt;&gt; thisistech()<br \/>\nthis is true<br \/>\n&gt;&gt;&gt;<\/div>\n<h2>Conclusion<\/h2>\n<p>Having learnt Generators vs Iterators in Python, now we know that coders can easily interpret and manipulate these two, but this is only possible with practice.<\/p>\n<p>We also learnt how a coder can easily use generators to make code more efficient.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we\u2019ll mainly learn about the difference between iterator and generator in Python, but of course, we need to know them separately as well. Let&#8217;s start!!!! What is Python Generators A python&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":80182,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1053],"tags":[1508,3349,3350,3351,1473,3352],"class_list":["post-80181","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-generators-in-python","tag-iterator-and-generator-in-python","tag-iterator-vs-generator-in-python","tag-iterator-vsgenerator-in-python","tag-iterators-in-python","tag-iterators-vs-generators"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Difference between Iterator and Generator in Python - TechVidvan<\/title>\n<meta name=\"description\" content=\"Learn the comparison between Iterator and Generator in Python. Understand generators vs iterators with examples.\" \/>\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-vs-iterators\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Difference between Iterator and Generator in Python - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Learn the comparison between Iterator and Generator in Python. Understand generators vs iterators with examples.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/python-generators-vs-iterators\/\" \/>\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=\"2021-01-20T03:30:21+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-Generators-vs-Iterators-tv.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\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":"Difference between Iterator and Generator in Python - TechVidvan","description":"Learn the comparison between Iterator and Generator in Python. Understand generators vs iterators with examples.","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-vs-iterators\/","og_locale":"en_US","og_type":"article","og_title":"Difference between Iterator and Generator in Python - TechVidvan","og_description":"Learn the comparison between Iterator and Generator in Python. Understand generators vs iterators with examples.","og_url":"https:\/\/techvidvan.com\/tutorials\/python-generators-vs-iterators\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2021-01-20T03:30:21+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-Generators-vs-Iterators-tv.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-vs-iterators\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-generators-vs-iterators\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Difference between Iterator and Generator in Python","datePublished":"2021-01-20T03:30:21+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-generators-vs-iterators\/"},"wordCount":624,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-generators-vs-iterators\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-Generators-vs-Iterators-tv.jpg","keywords":["generators in python","Iterator and Generator in Python","Iterator vs Generator in Python","Iterator vsGenerator in Python","iterators in python","Iterators vs generators"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/python-generators-vs-iterators\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/python-generators-vs-iterators\/","url":"https:\/\/techvidvan.com\/tutorials\/python-generators-vs-iterators\/","name":"Difference between Iterator and Generator in Python - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-generators-vs-iterators\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-generators-vs-iterators\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-Generators-vs-Iterators-tv.jpg","datePublished":"2021-01-20T03:30:21+00:00","description":"Learn the comparison between Iterator and Generator in Python. Understand generators vs iterators with examples.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-generators-vs-iterators\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/python-generators-vs-iterators\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/python-generators-vs-iterators\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-Generators-vs-Iterators-tv.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-Generators-vs-Iterators-tv.jpg","width":1200,"height":628,"caption":"Difference between Python Generators and Iterators"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/python-generators-vs-iterators\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Difference between Iterator and Generator in Python"}]},{"@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\/80181","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=80181"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/80181\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/80182"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=80181"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=80181"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=80181"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}