avatarOliver S

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

1950

Abstract

it__</code>), but needs to return the iterator itself. <code>iter</code> is then actually used for iterating over the object, returning one element per call — and raises a <code>StopIteration()</code> if no more elements are available.</p><p id="56eb">Let us showcase this by defining an iterator which returns the first <code>n</code> square numbers:</p><div id="76f8"><pre><span class="hljs-keyword">class</span> <span class="hljs-title class_">SquareIterator</span>: <span class="hljs-keyword">def</span> <span class="hljs-title function_">init</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span>, n</span>): <span class="hljs-variable language_">self</span>.i = <span class="hljs-number">0</span> <span class="hljs-variable language_">self</span>.n = n

<span class="hljs-keyword">def</span> <span class="hljs-title function_">__iter__</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span></span>):
    <span class="hljs-keyword">return</span> <span class="hljs-variable language_">self</span>

<span class="hljs-keyword">def</span> <span class="hljs-title function_">__next__</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span></span>):
    <span class="hljs-keyword">if</span> <span class="hljs-variable language_">self</span>.i &lt; <span class="hljs-variable language_">self</span>.<span class="hljs-symbol">n:</span>
        i = <span class="hljs-variable language_">self</span>.i
        <span class="hljs-variable language_">self</span>.i += <span class="hljs-number">1</span>
        <span class="hljs-keyword">return</span> i**<span class="hljs-number">2</span>
    <span class="hljs-symbol">else:</span>
        <span class="hljs-keyword">raise</span> <span class="hljs-title class_">StopIteration</span>()</pre></div><p id="f6dd">As promised, we can now do all the things we can d

Options

o with “default” iterators you might have used before, such as:</p><div id="9317"><pre><span class="hljs-variable">for</span> <span class="hljs-variable">x</span> <span class="hljs-variable"><span class="hljs-keyword">in</span></span> <span class="hljs-function"><span class="hljs-title">SquareIterator</span>(<span class="hljs-number">5</span>): <span class="hljs-title">print</span>(<span class="hljs-variable">x</span>)</span>

<span class="hljs-function"><span class="hljs-title">print</span>(<span class="hljs-title">sum</span>(<span class="hljs-title">SquareIterator</span>(<span class="hljs-number">5</span>)))</span></pre></div><p id="9c06">This post is part of a series show-casing important Python concepts quickly. You can find the other parts here:</p><ul><li>Part 1: <a href="https://readmedium.com/lambda-functions-in-python-a124cebc2e99">Lambda Functions in Python</a></li><li>Part 3: <a href="https://readmedium.com/generators-and-generator-expressions-in-python-a8d2e700945e">Generators and Generator Expressions in Python</a></li><li>Part 4: <a href="https://readmedium.com/advanced-iteration-in-python-with-enumerate-and-zip-676b31ceac44">Advanced Iteration in Python with enumerate() and zip()</a></li><li>Part 5: <a href="https://readmedium.com/managing-resources-in-python-with-context-managers-with-statement-f07afc1afb4f">Managing Resources in Python with Context Managers (with statement)</a></li><li>Part 6: <a href="https://readmedium.com/generating-temporary-files-and-directories-in-python-dfc11f017a97">Generating Temporary Files and Directories in Python</a></li><li>Part 7: <a href="https://readmedium.com/logging-in-python-3df84ce78cef">Logging in Python</a></li><li>Part 8: <a href="https://readmedium.com/partial-functions-in-python-66998eef1384">Partial Functions in Python</a></li><li>Part 9: <a href="https://readmedium.com/f-strings-in-python-80e30c64fb95">f-Strings in Python</a></li></ul></article></body>

Iterators in Python

Python Shorts — Part 2

Photo by Chris Ried on Unsplash

An iterator in Python is an object which can be iterated over — i.e. it has a set number of elements, and we can loop over these.

This concept is for example used in for loops:

my_list = [0, 1, 2, 3, 4]
for el in my_list:
    print(el)

Under the hood, an iterator needs to implement the functions __iter__ and __next__, which we will investigate in a bit.

Many other functions, such as list() or sum(), work with iterators:

print(sum(my_list))

Behind the Scenes

Now let’s go a bit deeper and understand what is going on behind the scenes — and implement our own iterator.

As stated above, iterators need to implement the functions __iter__ and __next__. __iter__ is similar to the constructor of common classes (__init__), but needs to return the iterator itself. __iter__ is then actually used for iterating over the object, returning one element per call — and raises a StopIteration() if no more elements are available.

Let us showcase this by defining an iterator which returns the first n square numbers:

class SquareIterator:
    def __init__(self, n):
        self.i = 0
        self.n = n

    def __iter__(self):
        return self

    def __next__(self):
        if self.i < self.n:
            i = self.i
            self.i += 1
            return i**2
        else:
            raise StopIteration()

As promised, we can now do all the things we can do with “default” iterators you might have used before, such as:

for x in SquareIterator(5):
    print(x)

print(sum(SquareIterator(5)))

This post is part of a series show-casing important Python concepts quickly. You can find the other parts here:

Python
Python Iterator
Recommended from ReadMedium