How to modify list entries during for loop?
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Updating list data during iteration is common in Python, but the safe pattern depends on the kind of change you need. Replacing existing values is usually straightforward, while inserting or removing elements can break iteration order. The best approach is to choose an iteration strategy that matches the mutation type.
Replacing Values In Place
If list length stays the same, iterate by index and assign directly. This is simple, predictable, and memory efficient.
Output:
enumerate works well too when you want both index and value.
Building a New List for Complex Transformations
When transformation logic is heavy, producing a new list is often clearer than mutating in place.
This keeps original data unchanged, which is useful when debugging and writing tests.
List comprehension is the compact version.
Removing Items Safely
Removing entries while looping forward over the same list can skip elements because indices shift left after each deletion. Use one of the safe patterns below.
Pattern one uses a filtered copy.
Pattern two iterates backward by index for in place deletion.
Backward iteration works because deleting a higher index does not affect earlier indices that are still pending.
Inserting Items Without Breaking Iteration
Inserting into the same list during a standard loop can create duplicated work or infinite loops. If you must insert, use a while loop with explicit index control.
This pattern makes index movement explicit so each insertion is deterministic.
Performance and Readability Tradeoffs
In place updates avoid extra allocation and can be faster for very large lists. New-list approaches are often easier to reason about and reduce accidental side effects. In real projects, readability usually matters more unless profiling proves mutation is required.
If your code performs many random insertions and deletions, consider collections.deque or a different data model. Python lists are dynamic arrays, so middle operations can be expensive.
Common Pitfalls
- Deleting while iterating forward. Fix by iterating backward or rebuilding via filtering.
- Modifying list length inside a
for item in listloop. Fix by switching to index orwhilecontrol. - Forgetting whether mutation should affect original data. Fix by choosing in place assignment versus returned copy intentionally.
- Hiding complex mutation in one line comprehensions. Fix by expanding to multi-line loops when logic grows.
- Assuming all changes are equally cheap. Fix by remembering that middle inserts and deletes are costly for long lists.
Summary
- Use index iteration or
enumeratefor in place replacement. - Build a new list for clarity and safer transformations.
- Remove items with filtering or reverse index loops.
- Insert items only with explicit index control such as
whileloops. - Match technique to mutation type to avoid skipped elements and hard-to-find bugs.
Related reading
- How to monitor queue health in celery
- How to move duplicates to the end of an array while preserving order in C?
- How to normalize a numpy array to a unit vector
- How to normalize a NumPy array to within a certain range?
- How to move a model between two Django apps Django 1.7
- How to Multi-thread an Operation Within a Loop in Python
- How to obtain the index permutation after the sorting
- How to optimally divide an array into two subarrays so that sum of elements in both are same, otherwise give an error?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.