Search code examples
pythonlistfor-loopiteration

Going back to an earlier index in list iteration


I have this loop over a list:

MyList = ["test", "test2", "test3", "test4", "test5", "test6", "test7"]

for item in MyList:
    print(item) # output: [test, test2, test3, test4, test5, test6, test7]
    if item == "test7":
        pass  # ?

Now in here if item == "test7" I want to go back to the third item ("test3") and go count up again.

How can I do that?

I have to use a for loop. I can't really use a while loop.


Solution

  • change the new_start_index to whatever you want and just do another for loop.

    MyList = ["test", "test2", "test3", "test4", "test5", "test6", "test7"]
    
    for item in MyList:
        print(item)
        if item == "test7":
            new_start_index = 3
            # Continue the loop from the new_start_index
            for new_item in MyList[new_start_index:]:
                print(new_item)