Popular recipes tagged "iteration"http://code.activestate.com/recipes/tags/iteration/popular/2014-03-29T12:43:26-07:00ActiveState Code RecipesEasily Write Nested Loops (Python)
2012-02-18T01:34:55-08:00Stephen Chappellhttp://code.activestate.com/recipes/users/2608421/http://code.activestate.com/recipes/578046-easily-write-nested-loops/
<p style="color: grey">
Python
recipe 578046
by <a href="/recipes/users/2608421/">Stephen Chappell</a>
(<a href="/recipes/tags/iteration/">iteration</a>, <a href="/recipes/tags/nested/">nested</a>).
</p>
<p>The "nest" generator function in this module is provided to make writing
nested loops easier to accomplish. Instead of writing a for loop at each
level, one may call "nest" with each sequence as an argument and receive
items from the sequences correctly yielded back to the caller. A test is
included at the bottom of this module to demonstrate how to use the code.</p>
map_longest and map_strict (Python)
2011-05-06T17:35:17-07:00Steven D'Apranohttp://code.activestate.com/recipes/users/4172944/http://code.activestate.com/recipes/577687-map_longest-and-map_strict/
<p style="color: grey">
Python
recipe 577687
by <a href="/recipes/users/4172944/">Steven D'Aprano</a>
(<a href="/recipes/tags/iteration/">iteration</a>, <a href="/recipes/tags/map/">map</a>).
Revision 2.
</p>
<p>In Python 3, the map builtin silently drops any excess items in its input:</p>
<pre class="prettyprint"><code>>>> a = [1, 2, 3]
>>> b = [2, 3, 4]
>>> c = [3, 4, 5, 6, 7]
>>> list(map(lambda x,y,z: x*y+z, a, b, c))
[5, 10, 17]
</code></pre>
<p>In Python 2, map pads the shorter items with None, while itertools.imap drops the excess items. Inspired by this, and by itertools.zip_longest, I have map_longest that takes a value to fill missing items with, and map_strict that raises an exception if a value is missing.</p>
<pre class="prettyprint"><code>>>> list(map_longest(lambda x,y,z: x*y+z, a, b, c, fillvalue=0))
[5, 10, 17, 6, 7]
>>> list(map_strict(lambda x,y,z: x*y+z, a, b, c))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 9, in map_strict
ValueError: too few items in iterable
</code></pre>
Reversed Ranges (Python)
2014-03-29T12:43:26-07:00Tal Einathttp://code.activestate.com/recipes/users/2892534/http://code.activestate.com/recipes/576801-reversed-ranges/
<p style="color: grey">
Python
recipe 576801
by <a href="/recipes/users/2892534/">Tal Einat</a>
(<a href="/recipes/tags/iteration/">iteration</a>, <a href="/recipes/tags/range/">range</a>, <a href="/recipes/tags/reverse/">reverse</a>).
Revision 16.
</p>
<p>A simple function for efficiently iterating over ranges in reverse.</p>
<p>This is equivalent to reversed(range(...)) but somewhat more efficient.</p>