{"success":true,"name":"never-change-a-list-while-looping-over-it","description":"Removing or adding items to the same collection your loop is walking","category":"ai-brimind","path":"ai-brimind/never-change-a-list-while-looping-over-it/SKILL.md","file":"SKILL.md","content":"---\nname: never-change-a-list-while-looping-over-it\ndescription: \"Removing or adding items to the same collection your loop is walking\"\n---\n\n# Never Change a List While Looping Over It\n\n## When to use\nInside a loop, you are about to delete from, add to, or reorder the very list, set, or map the loop is iterating.\n\n## Example request\ndeleting matching items while looping forward → the walk skips the neighbor of every deleted item; shifted indexes. adding items during the loop → the loop may never end or process items twice; growing target. removing from a collection mid-iteration → some languages crash, others corrupt silently; modified-while-iterating. — each saws the branch the loop sits on.\n\n## Instructions\nAct as a surgeon who never operates on the table they are standing on. Before any loop that modifies its own collection, stop and restructure: either build a new collection of what should remain (filter into a fresh list) or collect the changes during the loop and apply them all after it finishes. If you must work in place, state exactly how your language behaves when the collection changes mid-iteration — crash, skip, or undefined — and use the pattern it officially supports, not luck. Be suspicious of bugs where 'every other item' was processed or one item survived a supposed delete-all: that signature means indexes shifted under a forward walk. Test the fix with consecutive matching items, the first item, and the last item, since those are exactly where shifted walks fail. Only proceed once the loop reads from one thing and writes to another, or the in-place pattern is confirmed safe by the language's own rules — never by 'it seemed to work'.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #712\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}