Ran update-copyright.py
[hooke.git] / hooke / util / itertools.py
1 # Copyright (C) 2010-2012 W. Trevor King <wking@tremily.us>
2 #
3 # This file is part of Hooke.
4 #
5 # Hooke is free software: you can redistribute it and/or modify it under the
6 # terms of the GNU Lesser General Public License as published by the Free
7 # Software Foundation, either version 3 of the License, or (at your option) any
8 # later version.
9 #
10 # Hooke is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
13 # details.
14 #
15 # You should have received a copy of the GNU Lesser General Public License
16 # along with Hooke.  If not, see <http://www.gnu.org/licenses/>.
17
18 from __future__ import absolute_import
19
20 from itertools import izip
21
22
23 def reverse_enumerate(x):
24     """Iterate through `enumerate(x)` backwards.
25
26     This is a memory-efficient version of `reversed(list(enumerate(x)))`.
27     
28
29     Examples
30     --------
31     >>> a = ['a', 'b', 'c']
32     >>> it = reverse_enumerate(a)
33     >>> type(it)
34     <type 'itertools.izip'>
35     >>> list(it)
36     [(2, 'c'), (1, 'b'), (0, 'a')]
37     >>> list(reversed(list(enumerate(a))))
38     [(2, 'c'), (1, 'b'), (0, 'a')]
39
40     Notes
41     -----
42     `Original implemenation`_ by Christophe Simonis.
43
44     .. _Original implementation:
45       http://christophe-simonis-at-tiny.blogspot.com/2008/08/python-reverse-enumerate.html
46     """
47     return izip(xrange(len(x)-1, -1, -1), reversed(x))
48
49 #  LocalWords:  itertools