Loading section...
Modifying While Looping
Modifying a collection while iterating over it is dangerous and often causes bugs. Elements get skipped or the iterator becomes invalid. However, with the right techniques, you can safely modify collections during iteration. Before looking at specific techniques, here are the three safe strategies you can rely on whenever you need to change a collection mid-loop. The Problem Removing elements while iterating forward causes items to be skipped because indices shift: When you remove index 0, element at index 1 moves to index 0. But the iterator advances to index 1, skipping what is now at index 0. Solution 1: Copy, Then Iter Create a copy of the list and iterate over it while modifying the original: Solution 2: Reverse Iter As shown earlier, iterating backwards keeps all earlier indices vali