Search code examples
pythongeneratorreverse

Python Reverse Generator


I'm looking for a way to reverse a generator object. I know how to reverse sequences:

foo = imap(seq.__getitem__, xrange(len(seq)-1, -1, -1))

But is something similar possible with a generator as the input and a reversed generator as the output (len(seq) stays the same, so the value from the original sequence can be used)?


Solution

  • You cannot reverse a generator in any generic way except by casting it to a sequence and creating an iterator from that. Later terms of a generator cannot necessarily be known until the earlier ones have been calculated.

    Even worse, you can't know if your generator will ever hit a StopIteration exception until you hit it, so there's no way to know what there will even be a first term in your sequence.

    The best you could do would be to write a reversed_iterator function:

    def reversed_iterator(iter):
        return reversed(list(iter))
    

    EDIT: You could also, of course, replace reversed in this with your imap based iterative version, to save one list creation.