Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'continue' the 'for' loop to the previous element

I have been trying to find a way to continue my for loop to the previous element. It's hard to explain.

Just two be clear, here is an example:

foo = ["a", "b", "c", "d"]

for bar in foo:
    if bar == "c":
        foo[foo.index(bar)] = "abc"
        continue
    print(bar)

On executing this, when the loop reaches to 'c', it sees that bar is equal to 'c', it replaces that 'c' in the list, continues to the next element & doesn't print bar. I want this to loop back to 'b' after replacing when the if condition is true. So it will print 'b' again and it will be just like the loop never reached 'c'

Background: I am working on a project. If any error occurs, I have to continue from the previous element to solve this error.

Here is a flowchart, if it can help:

Flow chart

I prefer not to modify my existing list except for the replacing I made. I tried searching through every different keyword but didn't found a similar result.

How do I continue the loop to the previous element of the current one?

like image 827
Black Thunder Avatar asked Sep 02 '19 05:09

Black Thunder


People also ask

How do you use continue in a for loop?

The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop. In a for loop, the continue keyword causes control to immediately jump to the update statement.

How do you continue a for loop in Python?

The continue keyword is used to end the current iteration in a for loop (or a while loop), and continues to the next iteration.

Does continue skip the iteration?

The continue statement skips the rest of the instructions in a for or while loop and begins the next iteration. To exit the loop completely, use a break statement. continue is not defined outside a for or while loop. To exit a function, use return .

How do you move to the next element in a list Python?

To access the next element in list , use list[index+1] and to access the previous element use list[index-1] .


2 Answers

Here when the corresponding value of i is equal to c the element will change to your request and go back one step, reprinting b and abc, and finally d:

foo = ["a", "b", "c", "d"]
i = 0
while i < len(foo):
    if foo[i] == "c":
        foo[i] = "abc"
        i -= 1
        continue
    print(foo[i])
    i += 1
like image 76
Ahmad Avatar answered Sep 28 '22 13:09

Ahmad


In a for loop you cannot change the iterator. Use a while loop instead:

foo = ["a", "b", "c", "d"]
i = 0
while i < len(foo):
    if foo[i] == "c":
        foo[foo.index(foo[i])] = "abc"
        i -= 1
        continue
    print(foo[i])
    i += 1    
like image 43
Aryerez Avatar answered Sep 28 '22 15:09

Aryerez