Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a python iterator go backwards?

Is there anyway to make a python list iterator to go backwards?

Basically i have this

class IterTest(object):     def __init__(self, data):         self.data = data         self.__iter = None      def all(self):         self.__iter = iter(self.data)         for each in self.__iter:             mtd = getattr(self, type(each).__name__)             mtd(each)      def str(self, item):         print item          next = self.__iter.next()         while isinstance(next, int):             print next             next = self.__iter.next()      def int(self, item):         print "Crap i skipped C"  if __name__ == '__main__':     test = IterTest(['a', 1, 2,3,'c', 17])     test.all() 

Running this code results in the output:

a 1 2 3 Crap i skipped C 

I know why it gives me the output, however is there a way i can step backwards in the str() method, by one step?

EDIT

Okay maybe to make this more clear. I don't want to do a full reverse, basically what i want to know if there is an easy way to do the equivalent of a bidirectional iterator in python?

like image 483
UberJumper Avatar asked May 05 '10 22:05

UberJumper


People also ask

Can an iterator go backwards?

C++ Iterators Reverse IteratorsTo iterate backwards use rbegin() and rend() as the iterators for the end of the collection, and the start of the collection respectively.

How do I iterate a list backwards in Python?

Use the reversed() Function to Traverse a List in Reverse Order in Python. We can traverse a list in Python in reverse order by using the inbuilt reversed() function available. The reversed() function returns the reversed iteration of the sequence provided as input.

What is the opposite of next in Python?

itertools 'previous' (opposite of next) python.

What does ITER function do in Python?

The iter() function returns an iterator object.


1 Answers

No, in general you cannot make a Python iterator go backwards. However, if you only want to step back once, you can try something like this:

def str(self, item):     print item      prev, current = None, self.__iter.next()     while isinstance(current, int):         print current         prev, current = current, self.__iter.next() 

You can then access the previous element any time in prev.

If you really need a bidirectional iterator, you can implement one yourself, but it's likely to introduce even more overhead than the solution above:

class bidirectional_iterator(object):     def __init__(self, collection):         self.collection = collection         self.index = 0      def next(self):         try:             result = self.collection[self.index]             self.index += 1         except IndexError:             raise StopIteration         return result      def prev(self):         self.index -= 1         if self.index < 0:             raise StopIteration         return self.collection[self.index]      def __iter__(self):         return self 
like image 62
Tamás Avatar answered Sep 20 '22 03:09

Tamás