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.