Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reset a list iterator in Python?

For example, in C++ I could do the following :-

for (i = 0; i < n; i++){
    if(...){              //some condition
        i = 0;
    }
}

This will effectively reset the loop, i.e. start the loop over without introducing a second loop

For Python -

for x in a: # 'a' is a list
    if someCondition == True:
        # do something

Basically during the course of the loop the length of 'a' might change. So every time the length of 'a' changes, I want to start the loop over. How do I go about doing this?

like image 300
Rahul Sankar Avatar asked May 19 '18 16:05

Rahul Sankar


People also ask

Can you reset iterator python?

But remember that, iterators cannot go back or cannot be reset. Let's learn more about the __next__ function: The __next__() method takes no arguments and always returns the next element of the stream. If there are no more elements in the stream, __next__() must raise the StopIteration exception.

How do you reset an iterator?

Iterator has no reset method. To start again at the beginning, just get a new Iterator by calling iterator() again.

How do you stop iterations?

To prevent the iteration to go on forever, we can use the StopIteration statement.

What do iterators return?

Specifically, an iterator is any object which implements the Iterator protocol by having a next() method that returns an object with two properties: value. The next value in the iteration sequence.


1 Answers

You could define your own iterator that can be rewound:

class ListIterator:
    def __init__(self, ls):
        self.ls = ls
        self.idx = 0
    def __iter__(self):
        return self
    def rewind(self):
        self.idx = 0
    def __next__(self):
        try:
            return self.ls[self.idx]
        except IndexError:
            raise StopIteration
        finally:
            self.idx += 1

Use it like this:

li = ListIterator([1,2,3,4,5,6])
for element in li:
    ... # do something
    if some_condition:
        li.rewind()
like image 147
L3viathan Avatar answered Oct 19 '22 09:10

L3viathan