8

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?

Nouman
  • 6,947
  • 7
  • 32
  • 60

4 Answers4

6

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
Ahmad
  • 1,618
  • 5
  • 24
  • 46
  • I never talked about `while` in my question and all the answers are using `while`. – Nouman Sep 02 '19 at 05:41
  • 1
    you cannot use for because it cannot help you! – Ahmad Sep 02 '19 at 05:42
  • 1
    No. I can use `for`. I answered my own question. I knew there must be a way. I am not going to undo acceptance of your answer, but I want you to take a look at it. – Nouman Sep 05 '19 at 09:40
4

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    
Nouman
  • 6,947
  • 7
  • 32
  • 60
Aryerez
  • 3,417
  • 2
  • 9
  • 17
3

I wanted to use for so I created the code myself. I didn't want to modify my original list so I made a copy of my original list

foo = ["a", "b", "c", "d"]
foobar = foo.copy()

for bar in foobar:
    if bar == "c":
        foobar[foobar.index(bar)] = "abc"
        foo[foo.index(bar)] = "abc"
        del foobar[foobar.index("abc")+1:]
        foobar += foo[foo.index("abc")-1:]
        continue
    print(bar)

It prints as expected:

a
b
b
abc
d

And my original list also is now:

['a', 'b', 'abc', 'd']
Nouman
  • 6,947
  • 7
  • 32
  • 60
1
import collections
left, right = -1,1
foo = collections.deque(["a", "b", "c", "d"])
end = foo[-1]
while foo[0] != end:
    if foo[0] == 'c':
        foo[0] = 'abc'
        foo.rotate(right)
    else:
        print(foo[0])
        foo.rotate(left)
print(foo[0])
wwii
  • 23,232
  • 7
  • 37
  • 77