5

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?

4
  • 2
    You'll likely need to use a while loop, or recursion. Commented May 19, 2018 at 16:54
  • Are values in the list being changed as you loop through them; are you just appending values to the end or inserting values into the list? Commented May 19, 2018 at 16:58
  • @SeanBreckenridge: Based on some condition, I'm appending values to the list. So every time I append a value, I want the loop to start over Commented May 19, 2018 at 17:00
  • @miradulo: But for that I'll need a variable to keep track of the length of my list. Is there no other way to do it? Commented May 19, 2018 at 17:01

2 Answers 2

9

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()
Sign up to request clarification or add additional context in comments.

Comments

4

Not using for, but doing by hand with a while loop:

n = len(a)
i = 0
while i < n:
  ...
  if someCondition:
    n = len(a)
    i = 0
    continue
  i+=1

edit - if you're just appending to the end, do you really need to start over? You can just move the finish line further, by comparing i to len(a) directly, or calling n=len(a) in your loop

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.