{"id":1172,"date":"2020-11-16T07:02:54","date_gmt":"2020-11-16T07:02:54","guid":{"rendered":"https:\/\/www.pythontutorial.net\/?page_id=1172"},"modified":"2022-09-15T00:28:35","modified_gmt":"2022-09-15T00:28:35","slug":"python-iterators","status":"publish","type":"page","link":"https:\/\/www.pythontutorial.net\/advanced-python\/python-iterators\/","title":{"rendered":"Python Iterators"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn about Python iterator and how to define a custom iterator using the iterator protocol.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='what-is-a-python-iterator'>What is a Python iterator <a href=\"#what-is-a-python-iterator\" class=\"anchor\" id=\"what-is-a-python-iterator\" title=\"Anchor for What is a Python iterator\">#<\/a><\/h2>\n\n\n\n<p>An iterator is an object that implements:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><code>__iter__<\/code> method that returns the object itself.<\/li><li><code>__next__<\/code> method that returns the next item. If all the items have been returned, the method raises a <code>StopIteration<\/code> exception.<\/li><\/ul>\n\n\n\n<p class=\"note\">Note that these two methods are also known as the <strong>iterator protocol<\/strong>.<\/p>\n\n\n\n<p>Python allows you to use iterators in <code><a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-for-loop-list\/\">for<\/a><\/code> loops, comprehensions, and other built-in functions including <code><a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-map-list\/\">map<\/a><\/code>, <code><a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-filter-list\/\">filter<\/a><\/code>, <code><a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-reduce-list\/\">reduce<\/a><\/code>, and <code><a href=\"https:\/\/www.pythontutorial.net\/python-built-in-functions\/python-zip\/\">zip<\/a><\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='python-iterator-example'>Python iterator example <a href=\"#python-iterator-example\" class=\"anchor\" id=\"python-iterator-example\" title=\"Anchor for Python iterator example\">#<\/a><\/h2>\n\n\n\n<p>A square number is a product of an integer with itself. For example, a square of 2 is 4 (=2*2). <\/p>\n\n\n\n<p>The following example defines <code>Square<\/code> iterator class that returns the square numbers.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Square<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self, length)<\/span>:<\/span>\n        self.length = length\n        self.current = <span class=\"hljs-number\">0<\/span>\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__iter__<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">return<\/span> self\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__next__<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">if<\/span> self.current &gt;= self.length:\n            <span class=\"hljs-keyword\">raise<\/span> StopIteration\n\n        self.current += <span class=\"hljs-number\">1<\/span>\n        <span class=\"hljs-keyword\">return<\/span> self.current ** <span class=\"hljs-number\">2<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>How it works.<\/p>\n\n\n\n<p>First, initialize the <code>length<\/code> and <code>current<\/code> attributes in the <code>__init__<\/code> method.<\/p>\n\n\n\n<p>The <code>length<\/code> attribute specifies the number of square numbers that the class should return. And the <code>current<\/code> attribute keeps track of the current integer.<\/p>\n\n\n\n<p>Second, implement the <code>__iter__<\/code> method that returns the <code>self<\/code> object.<\/p>\n\n\n\n<p>Third, implement the <code>__next__<\/code> method that returns the next square number. If the number of square numbers has been returned is greater than the length, the<strong> <\/strong><code>__next__<\/code> method raises the <code>StopIteration<\/code> exception.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id='using-the-iterator-object'>Using the iterator object <a href=\"#using-the-iterator-object\" class=\"anchor\" id=\"using-the-iterator-object\" title=\"Anchor for Using the iterator object\">#<\/a><\/h3>\n\n\n\n<p>The following shows how to use the <code>Square<\/code> iterator in a <code>for<\/code> loop:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">square = Square(<span class=\"hljs-number\">5<\/span>)\n\n<span class=\"hljs-keyword\">for<\/span> sq <span class=\"hljs-keyword\">in<\/span> square:\n    print(sq)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">1\r\n4\r\n9\r\n16\r\n25<\/code><\/span><\/pre>\n\n\n<p>How it works:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>First, create a new instance of the <code>Square<\/code> class.<\/li><li>Then, use the <code>for<\/code> loop to iterate over items of the square iterator.<\/li><\/ul>\n\n\n\n<p>Once you iterate over all the items, the iterator is exhausted. It means you need to create a new iterator to iterate over its items again.<\/p>\n\n\n\n<p>If you attempt to use the iterator that is already exhausted, you&#8217;ll get the StopIteration exception. For example:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">next(square)<\/code><\/span><\/pre>\n\n\n<p>Error:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-built_in\">StopIteration<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Also, an iterator cannot be restarted because it only has the <code>__next__<\/code> method that returns the next item from a collection.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='summary'>Summary <a href=\"#summary\" class=\"anchor\" id=\"summary\" title=\"Anchor for Summary\">#<\/a><\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li>An iterator is an object that implements <code>__iter__<\/code> and <code>__next__<\/code> methods.<\/li><li>An iterator cannot be reusable once all items have been returned.<\/li><\/ul>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"1172\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/advanced-python\/python-iterators\/\"\n\t\t\t\tdata-post-title=\"Python Iterators\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"1172\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/advanced-python\/python-iterators\/\"\n\t\t\t\tdata-post-title=\"Python Iterators\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\t\t\t<input type=\"button\" name=\"wth-submit\" class=\"wth-btn wth-btn-submit\" id=\"wth-submit\" \/>\n\t\t\t<input type=\"button\" class=\"wth-btn wth-btn-cancel\" value=\"Cancel\" \/>\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you&#8217;ll learn about Python iterator and how to define a custom iterator using the iterator protocol.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":757,"menu_order":18,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-1172","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/1172","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/comments?post=1172"}],"version-history":[{"count":0,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/1172\/revisions"}],"up":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/757"}],"wp:attachment":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/media?parent=1172"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}