Python loop skipping irritation?

So I was trying to rename a bunch of files using the following python code I wrote.

#Enter link to folder
import os

File_Src=''

for i in input():

    if i!="\\":

        File_Src=File_Src+i

    else:

        File_Src=File_Src+i+"\\"

#File names 

File_names=os.listdir(File_Src)

#Renaming logic

renames=[]

for i in File_names:

    if "Chapter" in i:

        change=(i[i.index("Chapter"):i.index("Essence")])

        renames.append(change + i.replace(change, ""))

    else:

        File_names.remove(i)

if len(renames)==len(File_names):

    for i in range(len(renames)):

        os.rename(File_Src+"\\"+File_names[i],File_Src+"\\"+renames[i])

input()

It kept skipping one file. I managed to find that problem was in

for i in File_names:
    if "Chapter" in i:
        change=(i[i.index("Chapter"):i.index("Essence")])
        renames.append(change + i.replace(change, ""))
    else:
        File_names.remove(i)

But cant explain why this was happening.

Here is a much simpler version of the same code:

arr=[1,2,3,4,5,6,7]

for i in arr:
    if i!=4:
        print(i,end=" ")
    else:
        arr.remove(i)

#Output:1 2 3 6 7
#Expected:1 2 3 5 6 7

Please help.

What is happening here is a side-effect of changing array that’s being iterated.

2 Likes

Don’t change the array within the loop - because the for-in-loop still goes by the index and it is not tracking whatever changes you make to it.

2 Likes

Hello Sharon,

I have tried to solve the issue by setting the index at the previous position while iterating over the list and removing the specific element.

arr = [1, 2, 3, 4, 5, 6, 7]
element_removed = False

# iterate over list through index
    for j in range(len(arr)):
        if element_removed:
            j = j-1
        if arr[j] != 4:
            print(arr[j], end=" ")
        else:
            arr.remove(arr[j])
            element_removed = True
            
            # set element removed as true
            # so while iterating, an index can be set at a previous position and get all variables in a loop

I hope it might help. Please let me know if it is worked or not.

Thank you,
Akanxi Shah

Changing the array within the loop and backtracking the index is a bad approach. It works, but it is fragile and not the usual way to do this.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.