I want to save this thing I came across for future reference… a nice way to enumerate over an iterable in python in reverse order while retaining the proper indexes.

Here’s the issue. This code:

#!/usr/bin/python
    
WORDS = ['zero', 'one', 'two']

for index, string in enumerate(reversed(WORDS)):
    print index, string

… prints this:

0 two
1 one
2 zero

… which is “wrong” for our purposes. words[0] is not “two”, it is “zero”. So a quick web search for an elegant solution turned up a comment from “ΤΖΩΤΖΙΟΥ” on Christophe Simonis’ 2008 blog entry about reverse enumeration that has some code I really like:

import itertools
r_enumerate = lambda iterable: itertools.izip(reversed(xrange(len(iterable))), reversed(iterable))

Here’s the formatting I’m using:

#!/usr/bin/python
    
import itertools
    
def reverse_enumerate(iterable):
    """
    Enumerate over an iterable in reverse order while retaining proper indexes
    """
    return itertools.izip(reversed(xrange(len(iterable))), reversed(iterable))

And now the updated example code:

WORDS = ['zero', 'one', 'two']
    
for index, string in reverse_enumerate(WORDS):
    print index, string

… which prints this:

2 two
1 one
0 zero

… which is clearly the most exciting thing you’ve ever even heard about.