Report an Error

Reported page · Common Mistake

Mutating a List While Looping Over It

/mistakes/computer-science-mutating-a-list-while-looping-over-it/

or drop them here

Up to 3 images or PDFs, 5 MB per file. 0 of 3 attached.

Save resource to class

Loading your classrooms…

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.