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