5d12aa40c3e89160d7632e890a4d874148fe0ace
[hooke.git] / hooke / util / itertools.py
1 # Copyright
2
3 from __future__ import absolute_import
4
5 from itertools import izip
6
7
8 def reverse_enumerate(x):
9     """Iterate through `enumerate(x)` backwards.
10
11     This is a memory-efficient version of `reversed(list(enumerate(x)))`.
12     
13
14     Examples
15     --------
16     >>> a = ['a', 'b', 'c']
17     >>> it = reverse_enumerate(a)
18     >>> type(it)
19     <type 'itertools.izip'>
20     >>> list(it)
21     [(2, 'c'), (1, 'b'), (0, 'a')]
22     >>> list(reversed(list(enumerate(a))))
23     [(2, 'c'), (1, 'b'), (0, 'a')]
24
25     Notes
26     -----
27     `Original implemenation`_ by Christophe Simonis.
28
29     .. _Original implementation:
30       http://christophe-simonis-at-tiny.blogspot.com/2008/08/python-reverse-enumerate.html
31     """
32     return izip(xrange(len(x)-1, -1, -1), reversed(x))
33
34 #  LocalWords:  itertools