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, continue
s 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:
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?
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