Computer Science
Mutating a List While Looping Over It
Students remove or add items in a list while a loop is still iterating through that same list.
Quick check
Why students make it
They think the loop checks a fresh, stable version of the list each time. In many languages, the loop uses changing indices or an iterator, so deleting or inserting shifts items and can skip elements or cause errors.
The rule done right
Do not structurally modify the list you are directly looping over. Loop over a copy, build a new filtered list, or iterate by index carefully when mutation is required.
Related resources
- Linked List Operations Reference Cheat Sheet
- Programming Fundamentals Cheat Sheet
- Data Structures Overview Cheat Sheet
- AP Computer Science A Java Reference Cheat Sheet
- CS, Arrays and Lists Worksheet
- CS, Loops and Control Flow Worksheet
- Data Structures, Stacks, Queues, and Trees Worksheet
- Java Array & ArrayList Explorer Tool
- Data Structure Visualizer Tool
- Debugging & Unit Testing Explorer Tool
- Selection & Iteration Code Tracing Lab Lab
- Selection & Iteration Lab Lab
- Arrays & ArrayList Lab Lab
- Debugging & Unit Testing Lab Lab