Iterating over a sequence in reverse
28th January 2004
At work today we stumbled across a situation where we needed to display a list of items in reverse order. The decision to show them in reverse is made in the presentation layer, so altering the code that generates the list in the application logic layer would add coupling between the layers that we would rather avoid. Python’s reverse() function acts on a data structure in place, which we would rather avoid as well. Then we realised that Python’s generators could be used to create a proxy around the sequence allowing us to cycle through it in reverse without altering the sequence itself. Here’s the code:
class ReverseIteratorProxy:
def __init__(self, sequence):
self.sequence = sequence
def __iter__(self):
length = len(self.sequence)
i = length
while i > 0:
i = i - 1
yield self.sequence[i]
>>> l = range(10)
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for i in ReverseIteratorProxy(l):
... print i,
...
9 8 7 6 5 4 3 2 1 0
>>>
I was going to explain how the above code works, but after several false starts I realised that explaining generators is best left to the experts.
Update: Unsurprisingly, this isn’t exactly a new idea. PEP 322 covers reverse iteration, and the Python Tutorial uses it to illustrate both iterators and generators. Aah well.
More recent articles
- Qwen2.5-Coder-32B is an LLM that can code well that runs on my Mac - 12th November 2024
- Visualizing local election results with Datasette, Observable and MapLibre GL - 9th November 2024
- Project: VERDAD - tracking misinformation in radio broadcasts using Gemini 1.5 - 7th November 2024