'continue' the 'for' loop to the previous element
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