1. Why deleting during iteration often breaks your program
Imagine you are walking down a long corridor and counting doors. If, while you are counting, someone suddenly moves the walls, removes doors, and swaps them around, you will either lose count, start skipping doors, or even bump your forehead (the “forehead” role will be played by an exception). Collections behave the same way: iteration is a process that assumes the data structure is not being “rebuilt” under your feet.
The main reason deleting during iteration is dangerous is that the for mechanism (via an iterator) expects the collection not to change “outside the rules”. Kotlin/JVM collections can often detect such interference and respond with a ConcurrentModificationException. Sometimes there is no exception, but you get a logic error: you delete an element, indices shift, and the next element “slips past the check”.
In this lecture it is important to remember a practical formula: iteration and modification of a collection must be coordinated by the same mechanism. If iteration is done via an iterator — deletion must be done by the iterator. If iteration is done by indices — you must delete in a way that indices of elements not yet visited do not “shift”.
Forbidden pattern: remove(...) inside for (x in list)
Let’s start with the most popular “sin” that looks logical, readable and… sometimes works right up until the first real scenario. The logic seems ironclad: “I iterate elements; if an element is bad — I delete it.” But “iterate” and “delete” at that moment use different internal mechanisms, and they did not agree with each other.
fun main() {
val items = mutableListOf("keep", "remove", "keep")
for (x in items) {
if (x == "remove") {
items.remove(x) // 危險
}
}
println(items)
}
On the JVM this code often ends with ConcurrentModificationException: the iterator notices the collection was modified “behind its back” and stops in the most honest way — by crashing. Even if you got lucky and no exception happened, you should not rely on it: behavior depends on the collection implementation and the specific situation.
It’s important to catch the idea: for (x in items) uses an iterator under the hood, while items.remove(x) modifies the collection directly. It’s like driving with a GPS while someone rearranges roads in real time.
Forbidden pattern: deleting by indices from left to right
The second trap is more common among people who already understood that “you can’t delete inside for (x in list)”, and decided: “fine, I’ll iterate by indices — I control everything!”. Control does appear, but so does a new problem: deletion shifts elements to the left, while your index keeps growing to the right.
Let’s look at an example where we need to delete all "remove":
fun main() {
val items = mutableListOf("keep", "remove", "remove", "keep")
for (i in 0..items.lastIndex) {
if (items[i] == "remove") {
items.removeAt(i) // 從左往右時很危險
}
}
println(items)
}
Even if this code does not crash due to lastIndex changing (and it can easily crash with an index out of bounds), there is a subtler effect: when you delete items[1], the former items[2] moves into position 1. But the loop is already preparing to move to i = 2, and you simply won’t check that “moved” element. The result: some elements will not be deleted, and you get a bug without an exception. The most beloved type of bug: “the program doesn’t crash, but lies”.
To stop suffering like this, remember: if deleting by indices, you should go from the end to the beginning.
2. Strategy: delete via MutableIterator.remove()
Now comes the moment when collections suddenly become kind. Kotlin has a special iterator type for mutable collections — MutableIterator. It extends the usual Iterator and adds the method remove(), which deletes the “current” element correctly, i.e., in coordination with the iteration process.
Key idea: if iteration is controlled by an iterator, then the iterator must be the one deleting.
Here is a safe variant for deleting while iterating a list:
fun main() {
val items = mutableListOf("a", "remove", "b")
val it = items.iterator()
while (it.hasNext()) {
val x = it.next()
if (x == "remove") {
it.remove()
}
}
println(items) // [a, b]
}
Notice the “ritual”: we first call next() so the iterator “points” to the current element, and only after that can we call remove(). That is why people often say: remove() deletes the last element that was returned by next().
The iterator is one-shot
After you reach the end, this iterator is “exhausted”. If you need to walk through the collection again — create a new iterator via items.iterator(). This is not an error and not “wasteful”; it is the normal iteration model.
Mini-app example: cleaning empty strings
Let’s keep the practical style: imagine that in a project we have a shopping list, and the user sometimes adds junk (empty strings, spaces). We want to make a cleanup command that removes blank entries.
fun cleanupBlankItems(items: MutableList<String>) {
val it = items.iterator()
while (it.hasNext()) {
val name = it.next()
if (name.isBlank()) {
it.remove()
}
}
}
This function is small but useful: it shows exactly the case where deletion happens “by condition” during iteration, and here the iterator is the most reliable tool.
Contract of MutableIterator.remove(): how not to break the rules
The idea “delete via the iterator” sounds like salvation, but it comes with rules — not “nice to have” rules, but “otherwise you’ll get an exception” rules. If you break the contract, collections become angry again — and this time it’s on you.
The most common problem is calling remove() twice in a row without a new next(). Let’s show what you must not do:
fun main() {
val items = mutableListOf("remove", "x")
val it = items.iterator()
it.next()
it.remove()
// it.remove() // 不行:沒有第二次 next()
println(items) // [x]
}
The logic is simple: after remove() the iterator has already deleted the “last yielded element”. To delete again, the iterator must yield an element again via next(). If you try to delete again, the iterator cannot determine “what exactly you want to delete” and rightly complains.
In real projects, this usually appears not so explicitly but when complex branching logic sneaks into the loop body. That’s why a useful habit is to keep the loop body simple: “get element → check condition → delete if needed”.
3. Strategy: delete by indices from right to left
Sometimes an iterator is not the most convenient option. For example, your logic depends on the index: you delete “every third element”, delete a range, or you need to print the element number to the user. In such cases, it’s easier to think in indices. But then you must delete so that deletion does not affect elements you haven’t checked yet.
The focus here is that list indices go from 0 to lastIndex, where lastIndex == size - 1. If you go from end to start, deleting an element does not shift elements that are to the left. That means your “not yet checked” elements keep their indices.
Here is a safe example:
fun main() {
val items = mutableListOf("keep", "remove", "remove", "keep")
for (i in items.lastIndex downTo 0) {
if (items[i] == "remove") {
items.removeAt(i)
}
}
println(items) // [keep, keep]
}
Mini diagram: why right-to-left works
flowchart TD
A[從左到右走 i] --> B["刪除 items[i]"]
B --> C[右邊的元素往左移]
C --> D[下一個 i 會跳過一個元素]
D --> E[邏輯錯誤]
A2[從右到左走 i] --> B2["刪除 items[i]"]
B2 --> C2[只會移動右邊的元素,但右邊早就檢查完了]
C2 --> D2[左邊未檢查的元素索引不變]
D2 --> E2[邏輯正確]
4. How to choose a strategy in real code
In practice you will choose a strategy not by beauty, but by what you need in a specific operation. To avoid keeping all of this in your head as a “feeling”, it helps to have a small reminder table.
| Situation | Best fit | Why |
|---|---|---|
| Deleting elements by condition, index doesn’t matter | |
Iteration and deletion are done by the same “device”, fewer chances to make a mistake |
| Deleting from MutableList, but logic depends on index | Loop for (i in lastIndex downTo 0) + removeAt(i) | Indices of unchecked elements do not shift |
| Deleting from MutableMap during iteration | Iterator over entries + remove() | Deleting the “current entry” is coordinated with iteration |
| Deleting one element “by value” without iterating | |
No iteration is needed at all, so there is no conflict |
Note: the table does not say “always do this”. It says: “if you are already in situation X — here is the most predictable path”.
5. Safe deletion from MutableMap during iteration
Map is not a list; you cannot iterate it by indices. But you may still really want to delete from a MutableMap during iteration. For example, in our app we might have a MutableMap<String, Int> as a “warehouse”: product → quantity. And we want to clean out products where quantity became 0.
If you try to do stock.remove(key) inside for ((k, v) in stock), you get the same conflict: “iterate via iterator, delete directly”. The correct variant is an iterator over entries:
fun removeZeroStock(stock: MutableMap<String, Int>) {
val it = stock.entries.iterator()
while (it.hasNext()) {
val entry = it.next()
if (entry.value == 0) {
it.remove()
}
}
}
Why exactly entries? Because Map.Entry gives you both the key and the value at once, without a second lookup. And an iterator over entries can correctly delete the current pair. Conceptually, it is the same principle as with a list: the one who iterates should be the one who deletes.
6. Integrating into an app: data cleanup operations
In real programs, deletion during iteration rarely exists on its own. Usually it lives inside a “maintenance operation”: remove invalid records, remove empty elements, remove completed tasks, clean out zero stock. That’s why it’s useful to wrap such parts into separate functions — small and testable.
Suppose in our console app the shopping state is stored like this: each purchase is a Pair<String, Int>, where first is the product name, and second is the quantity. (We haven’t covered classes yet, so without a data class.)
Let’s write a function that deletes purchases with quantity <= 0. This is a classic “delete many elements by condition” case, so an iterator is perfect:
fun removeNonPositive(items: MutableList<Pair<String, Int>>) {
val it = items.iterator()
while (it.hasNext()) {
val item = it.next()
if (item.second <= 0) {
it.remove()
}
}
}
Now a case where indices are more convenient: suppose we want to delete all elements with the name "tmp" (the user added temporary entries), and we also want to print which lines we deleted, with their “number in the list at the moment of deletion”. Then we can go right-to-left, and numbers “to the right” no longer matter:
fun removeAllTmp(items: MutableList<String>) {
for (i in items.lastIndex downTo 0) {
if (items[i] == "tmp") {
items.removeAt(i)
}
}
}
Here it’s important not to try to make it “prettier” by switching to left-to-right: right-to-left is not a whim, it’s a correctness guarantee.
remove(value) vs removeAt(index): don’t mix up the meaning
When you write code that “deletes”, it is easy to start confusing: are you deleting by value or by position? This is especially noticeable in command-line apps, where the user enters remove 3 expecting “delete the third element”, but you accidentally do “delete an element with the value "3"”.
A MutableList usually has two different operations: deleting by value and deleting by index. In Kotlin this is expressed directly in the names: removeAt(i) deletes by position, while remove(x) deletes by value. When building commands, choose semantics in advance: either the remove command deletes by number (then you need removeAt and a check i in indices), or by value (then remove(value)), or you have two separate commands.
This matters in the context of today’s topic: if you delete “many elements” by condition, you will almost always either call removeAt many times or use an iterator. But if you delete exactly one element by value — you don’t need iteration at all.
7. Common mistakes in safe deletions
Mistake #1: deleting via the collection inside for (x in collection).
This looks natural, but conflicts with how for works: under the hood it uses an iterator, while you change the collection structure directly. A common result is ConcurrentModificationException, and sometimes even worse: “just weird behavior”. A reliable solution is to delete either via MutableIterator.remove(), or not delete during iteration at all.
Mistake #2: iterating indices left-to-right and doing removeAt(i) inside the loop.
Technically you “control everything”, but deletion shifts elements, and you easily skip parts of the collection or go out of bounds. If you choose the index style, there is one safe rule: delete right-to-left via for (i in lastIndex downTo 0).
Mistake #3: calling it.remove() against the contract, e.g. twice in a row.
MutableIterator.remove() deletes the element most recently returned by next(). If you call remove() before next() or repeat remove() without a new next(), the iterator cannot correctly determine the deletion target and will throw an exception. The discipline is simple: “next() → check → maybe remove()”.
Mistake #4: trying to delete from a Map while iterating keys, and in parallel doing map.remove(key).
Even if it seems “I delete by key, that’s logical”, the problem is the same: iteration and deletion use different mechanisms. A reliable approach: val it = map.entries.iterator() and delete via it.remove().
Mistake #5: mixing up “index” and “user-facing number”.
The user thinks “first element” and means 1, while the list thinks “first element” and means index 0. If you accept a delete command by number, always do index = number - 1 and check index in items.indices, otherwise you will either delete the wrong element or crash.
GO TO FULL VERSION