Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First of all the <a href="https://docs.python.org/3/library/itertools.html" rel="noreferrer">itertools module</a> is incredibly useful for all sorts of cases in which an iterator would be useful, but here is all you need to create an iterator in python:</p> <blockquote> <p>yield</p> </blockquote> <p>Isn't that cool? Yield can be used to replace a normal <strong>return</strong> in a function. It returns the object just the same, but instead of destroying state and exiting, it saves state for when you want to execute the next iteration. Here is an example of it in action pulled directly from the <a href="http://docs.python.org/lib/itertools-functions.html" rel="noreferrer">itertools function list</a>:</p> <pre><code> def count(n=0): while True: yield n n += 1 </code></pre> <p>As stated in the functions description (it's the <strong>count()</strong> function from the itertools module...) , it produces an iterator that returns consecutive integers starting with n.</p> <p><a href="https://docs.python.org/2/reference/expressions.html#generator-expressions" rel="noreferrer">Generator expressions</a> are a whole other can of worms (awesome worms!). They may be used in place of a <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk" rel="noreferrer">List Comprehension</a> to save memory (list comprehensions create a list in memory that is destroyed after use if not assigned to a variable, but generator expressions can create a Generator Object... which is a fancy way of saying Iterator). Here is an example of a generator expression definition:</p> <pre><code>gen = (n for n in xrange(0,11)) </code></pre> <p>This is very similar to our iterator definition above except the full range is predetermined to be between 0 and 10.</p> <p>I just found <strong>xrange()</strong> (suprised I hadn't seen it before...) and added it to the above example. <strong>xrange()</strong> is an iterable version of <strong>range()</strong> which has the advantage of not prebuilding the list. It would be very useful if you had a giant corpus of data to iterate over and only had so much memory to do it in.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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