{"id":3231,"date":"2020-02-09T18:14:50","date_gmt":"2020-02-09T18:14:50","guid":{"rendered":"https:\/\/www.askpython.com\/?p=3231"},"modified":"2022-08-06T13:10:54","modified_gmt":"2022-08-06T13:10:54","slug":"python-iterator","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/built-in-methods\/python-iterator","title":{"rendered":"Python Iterator"},"content":{"rendered":"\n<p>A Python Iterator is an object that can be iterated upon. Any kind of object that supports this kind of iteration is called as an <strong>iterator<\/strong>.<\/p>\n\n\n\n<p>Now, you may be confused. There exists another object called <strong>iterable<\/strong>. What is that? Let&#8217;s take a look.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Iterators and Iterables<\/h2>\n\n\n\n<p>Any iterable is an object that can be iterated upon. That is, we can use iterators to move through this object.<\/p>\n\n\n\n<p>Examples of Iterable objects are tuples, lists, strings, arrays, etc.<\/p>\n\n\n\n<p>To construct an <strong>iterator<\/strong> from an <em>iterable<\/em>, we can use the <code>iter()<\/code> method.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\niterable_list = &#x5B;1, 2, 3]\niterable_string = &quot;Hello&quot;\n\niterator_1 = iter(iterable_list)\niterator_2 = iter(iterable_string)\n\nprint(iterator_1, type(iterator_1))\nprint(iterator_2, type(iterator_2))\n<\/pre><\/div>\n\n\n<p>Output<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&lt;list_iterator object at 0x7f887b01aed0&gt; &lt;class &#039;list_iterator&#039;&gt;\n&lt;str_iterator object at 0x7f887b01af50&gt; &lt;class &#039;str_iterator&#039;&gt;\n<\/pre><\/div>\n\n\n<p>The output shows that we have created two iterators; one for the list and one for the string.<\/p>\n\n\n\n<p>Now let&#8217;s look at the methods which the iterator object supports.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Python Iterator Methods<\/h2>\n\n\n\n<p>An iterator object has two special methods that can be used with it, called <strong>iter()<\/strong> and <strong>next()<\/strong>.<\/p>\n\n\n\n<p>The <code>iter()<\/code> method was used earlier, to get a Python <strong>iterator<\/strong> object from an iterable. <\/p>\n\n\n\n<p>Now, to traverse through the iterator, we can use the <code>next()<\/code> method to get the next element in the iterable.<\/p>\n\n\n\n<p>Format:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nnext_iterable_object = next(iterator)\n<\/pre><\/div>\n\n\n<p>When there are no more elements left to go to, this will terminate and raise a <code>StopIteration<\/code> <a href=\"https:\/\/www.askpython.com\/python\/python-exception-handling\" class=\"rank-math-link\">Exception<\/a>.<\/p>\n\n\n\n<p>To illustrate all this, let&#8217;s print all the elements of our list iterator.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&gt;&gt;&gt; iterable_list = &#x5B;1, 2, 3]\n&gt;&gt;&gt; iterator_1 = iter(iterable_list)\n&gt;&gt;&gt; next(iterator_1)\n1\n&gt;&gt;&gt; next(iterator_1)\n2\n&gt;&gt;&gt; next(iterator_1)\n3\n&gt;&gt;&gt; next(iterator_1)\nTraceback (most recent call last):\n  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;\nStopIteration\n<\/pre><\/div>\n\n\n<p>As you can see, when you go beyond the length of the iterable, this indeed raises the <code>StopIteration<\/code> Exception.<\/p>\n\n\n\n<p>Now, let&#8217;s go to the next step: Making our own Iterator!<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Constructing our own Iterator in Python<\/h2>\n\n\n\n<p>Any iterator object has a countable number of elements, that can be traversed. But how can we make our own iterator? We need to create our own Class.<\/p>\n\n\n\n<p>In Python, constructing any iterator involves a protocol called the <strong>Iterator Protocol<\/strong>.<\/p>\n\n\n\n<p>This protocol contains two specific methods, called <code>__iter__()<\/code> and <code>__next__()<\/code>, similar to the general iterator methods, but since they are inside a class, it is prefixed and suffixed with this symbol, to show the distinction.<\/p>\n\n\n\n<p>The <code>iter()<\/code> and <code>next()<\/code> methods internally call these methods, and hence, to make the iterator, we need to define our own <code>__iter__()<\/code> and <code>__next__()<\/code> methods inside our class.<\/p>\n\n\n\n<p>Let&#8217;s create a simple iterator that traverses across a <strong>list<\/strong> only and raises a <strong>StopIteration<\/strong> Exception if the count of elements is greater than 5.<\/p>\n\n\n\n<p>We will also print the number of elements iterated so far, in our <code>next()<\/code> method.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nclass MyClass():\n    def __init__(self):\n        self.counter = 0\n        # Set the limit\n        self.limit = 5\n\n    def __iter__(self):\n        # The iter() method internally calls this\n        print(&#039;Call to __iter__()&#039;)\n        return self\n\n    def __next__(self):\n        print(&#039;Call to __next__()&#039;)\n        if self.counter &gt; self.limit:\n            raise StopIteration\n        else:\n            # Increment counter and return it\n            self.counter += 1\n            return self.counter\n\n\n# Create the iterable\nmy_obj = MyClass()\n\n# Create the iterator object from the iterable\nmy_it = iter(my_obj)\n\nfor i in range(7):\n    print(next(my_it))\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nCall to __iter__()\nCall to __next__()\n1\nCall to __next__()\n2\nCall to __next__()\n3\nCall to __next__()\n4\nCall to __next__()\n5\nCall to __next__()\n6\nCall to __next__()\nTraceback (most recent call last):\n  File &quot;iter.py&quot;, line 29, in &lt;module&gt;\n    print(next(my_it))\n  File &quot;iter.py&quot;, line 15, in __next__\n    raise StopIteration\nStopIteration\n<\/pre><\/div>\n\n\n<p>Here, this prints numbers from 1 to 6, and the next call will trigger the <code>StopIteration<\/code> exception, since we&#8217;ve crossed the limit.<\/p>\n\n\n\n<p>We&#8217;ve made our own iterator!<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>I hope you now have a good understanding of iterators and any doubts regarding this concept are cleared after reading this article. If not, do ask them in the comment section below!<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">References<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li>JournalDev article on Iterators<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n","protected":false},"excerpt":{"rendered":"<p>A Python Iterator is an object that can be iterated upon. Any kind of object that supports this kind of iteration is called as an iterator. Now, you may be confused. There exists another object called iterable. What is that? Let&#8217;s take a look. Iterators and Iterables Any iterable is an object that can be [&hellip;]<\/p>\n","protected":false},"author":7,"featured_media":3245,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[8],"tags":[],"class_list":["post-3231","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-built-in-methods"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/3231","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=3231"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/3231\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/3245"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=3231"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=3231"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=3231"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}