Going back to an earlier index in list iteration

63 views Asked by At

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.

3

There are 3 answers

0
Abduvohid Ilhomov On BEST ANSWER

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)
2
Rabbi Ofori Gyimah On

You can use indexing and for loop range.

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

for i in range(len(MyList)):
    print(MyList[i]) # output: [test, test2, test3, test4, test5, test6, test7]
    if item == "test7":
       i = i - 1

#so if you want to previous element, if i is not = 0 then is MyList[i-1] pass # ?

0
Martins On

try this...i don't know if its what you want.

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

for i, item in enumerate(MyList):
    print(item)
    if item == "test7":
        for j in range(starting_index, len(MyList)):
           
            print("Processing:", MyList[j])
        break