Kemp’s Blog

A technical blog about technical things

Python tips – Reverse iteration

This post, the first in what will be a sporadic series, relates to a mistake I saw recently when looking at through some Python code. The author had used the following method to iterate backwards through a list:

for i in range(len(foo)):
    print foo[-i]

It wasn’t a print in the original, it was something else which would have been far harder to spot had it introduced subtle errors into the results of the code. Given Python’s ability to index from the end of a list using negative indices, this seems to be a suitable solution. The problem here is that foo[-0] isn’t the last item in the list, foo[-1] is. The correct code the author was looking for was:

for item in reversed(foo):
    print item

Or, if you need the index of the item as well:

for i,value in enumerate(reversed(foo)):
    print i,item