Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Reverse Generator

Tags:

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)?

like image 870
ak. Avatar asked Oct 13 '09 16:10

ak.


People also ask

Can you reverse a generator Python?

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.

How do you reverse data in Python?

In Python, there is a built-in function called reverse() that is used to reverse the list. This is a simple and quick way to reverse a list that requires little memory. Syntax- list_name. reverse() Here, list_name means you have to write the name of the list which has to be reversed.

What is reverse in Python with example?

Python reversed() The reversed() method computes the reverse of a given sequence object and returns it in the form of a list.

How do you reverse a list in a for loop Python?

Another way to reverse python list without the use of any build-in methods is using loops. Create an empty list to copy the reversed elements. In the for loop, add the iterator as a list element at the beginning with the new list elements. So in that way, the list elements will be reversed.


1 Answers

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.

like image 153
jcdyer Avatar answered Sep 23 '22 17:09

jcdyer