'continue' the 'for' loop to the previous element
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Riding Sky Waves v001
--
Chapters
00:00 'Continue' The 'For' Loop To The Previous Element
01:06 Answer 1 Score 4
01:20 Accepted Answer Score 6
01:38 Answer 3 Score 1
01:48 Answer 4 Score 3
02:13 Thank you
--
Full question
https://stackoverflow.com/questions/5775...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #list #loops #continue
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Riding Sky Waves v001
--
Chapters
00:00 'Continue' The 'For' Loop To The Previous Element
01:06 Answer 1 Score 4
01:20 Accepted Answer Score 6
01:38 Answer 3 Score 1
01:48 Answer 4 Score 3
02:13 Thank you
--
Full question
https://stackoverflow.com/questions/5775...
--
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])