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?
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.
The continue keyword is used to end the current iteration in a for loop (or a while loop), and continues to the next 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 .
To access the next element in list , use list[index+1] and to access the previous element use list[index-1] .
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With