Python
Programming
For Loop
List Manipulation
Python Tips

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.

Practice algorithms

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.

python
1def normalize_scores(scores):
2    for i in range(len(scores)):
3        if scores[i] < 0:
4            scores[i] = 0
5        elif scores[i] > 100:
6            scores[i] = 100
7    return scores
8
9values = [95, 104, -5, 87]
10print(normalize_scores(values))

Output:

text
[95, 100, 0, 87]

enumerate works well too when you want both index and value.

python
1names = ["  Ada ", " Bob", "Caro  "]
2for i, name in enumerate(names):
3    names[i] = name.strip().title()
4
5print(names)

Building a New List for Complex Transformations

When transformation logic is heavy, producing a new list is often clearer than mutating in place.

python
1def transform(items):
2    result = []
3    for item in items:
4        if item % 2 == 0:
5            result.append(item * 10)
6        else:
7            result.append(item)
8    return result
9
10nums = [1, 2, 3, 4, 5]
11print(transform(nums))
12print(nums)

This keeps original data unchanged, which is useful when debugging and writing tests.

List comprehension is the compact version.

python
nums = [1, 2, 3, 4, 5]
updated = [n * 10 if n % 2 == 0 else n for n in nums]
print(updated)

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.

python
values = [3, 0, 5, 0, 7, 0]
values = [v for v in values if v != 0]
print(values)

Pattern two iterates backward by index for in place deletion.

python
1values = [3, 0, 5, 0, 7, 0]
2for i in range(len(values) - 1, -1, -1):
3    if values[i] == 0:
4        del values[i]
5
6print(values)

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.

python
1def expand_markers(tokens):
2    i = 0
3    while i < len(tokens):
4        if tokens[i] == "*":
5            tokens.insert(i + 1, "EXPANDED")
6            i += 2
7        else:
8            i += 1
9    return tokens
10
11arr = ["A", "*", "B", "*", "C"]
12print(expand_markers(arr))

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 list loop. Fix by switching to index or while control.
  • 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 enumerate for 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 while loops.
  • Match technique to mutation type to avoid skipped elements and hard-to-find bugs.

Related reading
Course
Intermediate
27 lessons
15 hours
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 course
Track 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.

Practice algorithms

All Rights Reserved.