The Python Oracle

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

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Switch On Looping

--

Chapters
00:00 Question
01:19 Accepted answer (Score 6)
01:41 Answer 2 (Score 4)
02:00 Answer 3 (Score 2)
02:37 Answer 4 (Score 0)
02:52 Thank you

--

Full question
https://stackoverflow.com/questions/5775...

Question links:
[image]: https://i.stack.imgur.com/e7y2z.png

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list #loops #continue

#avk47



ACCEPTED ANSWER

Score 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



ANSWER 2

Score 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    



ANSWER 3

Score 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']



ANSWER 4

Score 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])