Mutating a List While Iterating
Changing a list's structure during traversal can move elements relative to the iterator and cause a step to skip an item.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 2 min
In this article4 chapters
Trace two adjacent removals
Start with [0, 0, 1]. Removing the first zero shifts the next zero into position zero. A traversal that advances to position one then sees the value 1. The list can retain a zero. Use object and binding rules to confirm which list was changed.
Pick a traversal strategy
Building a filtered list avoids shifts during a traversal of the source. If an interface requires changing the original list, compute the kept entries first and then replace its contents deliberately. Shallow copying matters when selected items have nested mutable data.[1]
Trace the current offset and the shifted contents
Start with ["x", "x", "y"]. A normal index-based walk at position zero sees x and removes it. The list becomes ["x", "y"], with the second x now at zero. An iterator proceeding to position one can see y next, leaving one x unprocessed. Inserting a value before the current position can cause a previously visited item to be seen again. Draw the list after the structural change and mark the next offset. Zero-based indexing explains why the original index meanings no longer apply.
Pick a strategy that matches the ownership
If a consumer only needs the kept values, build a separate result while traversing the original list. If other callers share the original and expect its contents to change, first compute the new contents and then replace that list's items deliberately. Copying just the outer structure is sufficient for a stable list of entries but can share nested objects. See shallow copies.
Test two consecutive removable items at the start and at the end, plus a case where every element remains. Also check whether the original is expected to stay unchanged.