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