2
I finally understood why my Python loop kept skipping items
I was writing a script to remove all zeros from a list of numbers. I used a 'for' loop that checked each item and used '.remove()' if it was zero. After running it, some zeros were still there. I spent an hour confused until I realized that removing an item changes the list's length and index positions while the loop is running, so it skips the next item. I fixed it by creating a new list instead. Has anyone else run into this classic beginner trap?
2 comments
Log in to join the discussion
Log In2 Comments
oliver_torres44d ago
Classic. Did you try using a while loop instead? Iterating backwards from the end of the list also fixes the index shift problem.
1
the_drew4d ago
My brain defaults to for loops, honestly.
3