Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: <code>__iter__()</code> and <code>next()</code>. The <code>__iter__</code> returns the iterator object and is implicitly called at the start of loops. The <code>next()</code> method returns the next value and is implicitly called at each loop increment. <code>next()</code> raises a StopIteration exception when there are no more value to return, which is implicitly captured by looping constructs to stop iterating.</p> <p>Here's a simple example of a counter:</p> <pre><code>class Counter: def __init__(self, low, high): self.current = low self.high = high def __iter__(self): return self def next(self): # Python 3: def __next__(self) if self.current &gt; self.high: raise StopIteration else: self.current += 1 return self.current - 1 for c in Counter(3, 8): print c </code></pre> <p>This will print:</p> <pre><code>3 4 5 6 7 8 </code></pre> <p>This is easier to write using a generator, as covered in a previous answer:</p> <pre><code>def counter(low, high): current = low while current &lt;= high: yield current current += 1 for c in counter(3, 8): print c </code></pre> <p>The printed output will be the same. Under the hood, the generator object supports the iterator protocol and does something roughly similar to the class Counter.</p> <p>David Mertz's article, <a href="https://www.ibm.com/developerworks/library/l-pycon/" rel="noreferrer">Iterators and Simple Generators</a>, is a pretty good introduction. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload