22
TIL I was writing my Python loops backwards for months
I was building a simple script to rename files in a folder, and it kept skipping every other one. After staring at the screen for an hour, I printed the index at each step. I realized I was using 'for i in range(len(files), 0, -1)' when I just needed 'for i in range(len(files))'. Has anyone else had a simple syntax mistake that broke a whole project?
2 comments
Log in to join the discussion
Log In2 Comments
william_rivera17d ago
Check your loop body too. Were you trying to use that index to pop items from the list while iterating? I've done that before. Removing items changes the list length and the remaining indexes, which makes a reverse loop actually the right move sometimes. Your mistake might have been a fix for a different problem you didn't know you had.
6
barnes.shane17d ago
Actually used to think reverse loops were just for being fancy or showing off. Then I had to remove items from a list while going through it and everything broke. That one project made it click why you'd go backwards, so the indexes you haven't hit yet don't shift on you. Changed my whole view on when to use that pattern. What was the script you were working on?
1