1 # Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
3 # This file is part of Hooke.
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.
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.
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/>.
19 from __future__ import absolute_import
21 from itertools import izip
24 def reverse_enumerate(x):
25 """Iterate through `enumerate(x)` backwards.
27 This is a memory-efficient version of `reversed(list(enumerate(x)))`.
32 >>> a = ['a', 'b', 'c']
33 >>> it = reverse_enumerate(a)
35 <type 'itertools.izip'>
37 [(2, 'c'), (1, 'b'), (0, 'a')]
38 >>> list(reversed(list(enumerate(a))))
39 [(2, 'c'), (1, 'b'), (0, 'a')]
43 `Original implemenation`_ by Christophe Simonis.
45 .. _Original implementation:
46 http://christophe-simonis-at-tiny.blogspot.com/2008/08/python-reverse-enumerate.html
48 return izip(xrange(len(x)-1, -1, -1), reversed(x))
50 # LocalWords: itertools