Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I have found that generators are very helpful in cleaning up your code and by giving you a very unique way to encapsulate and modularize code. In a situation where you need something to constantly spit out values based on its own internal processing and when that something needs to be called from anywhere in your code (and not just within a loop or a block for example), generators are <em>the</em> feature to use.</p> <p>An abstract example would be a Fibonacci number generator that does not live within a loop and when it is called from anywhere will always return the next number in the sequence:</p> <pre><code>def fib(): first = 0 second = 1 yield first yield second while 1: next = first + second yield next first = second second = next fibgen1 = fib() fibgen2 = fib() </code></pre> <p>Now you have two Fibonacci number generator objects which you can call from anywhere in your code and they will always return ever larger Fibonacci numbers in sequence as follows:</p> <pre><code>&gt;&gt;&gt; fibgen1.next(); fibgen1.next(); fibgen1.next(); fibgen1.next() 0 1 1 2 &gt;&gt;&gt; fibgen2.next(); fibgen2.next() 0 1 &gt;&gt;&gt; fibgen1.next(); fibgen1.next() 3 5 </code></pre> <p>The lovely thing about generators is that they encapsulate state without having to go through the hoops of creating objects. One way of thinking about them is as "functions" which remember their internal state.</p> <p>I got the Fibonacci example from <em><a href="http://www.neotitans.com/resources/python/python-generators-tutorial.html" rel="nofollow noreferrer">Python Generators - What are they?</a></em> and with a little imagination, you can come up with a lot of other situations where generators make for a great alternative to <code>for</code> loops and other traditional iteration constructs.</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