+ 11

generator

Can anyone tell me how to reverse a generator in python?

8th Oct 2020, 4:09 PM
Hardik
Hardik - avatar
3 Answers
+ 11
No, it is not possible, because a generator is not subscriptable or reversible. The only way to output reversed data from a generator is to convert it to may be a list, and from this doing a reverse version. I am not sure you are really familiar with python as you mentioned. A generator "generates" one item after the other, so how should it be possible to know the last item a generator creates? If you need a reversed version of a generator, so just do it in a way that the generated sequence of items is in the way you like to get it. BTW, most of the answers to your questions you placed here, can be found by using google.
8th Oct 2020, 6:04 PM
Lothar
Lothar - avatar
+ 3
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))
10th Oct 2020, 3:01 PM
Kathula Vyshnavi
Kathula Vyshnavi - avatar