How to Modify a List While Iterating in Python
Modifying a list while iterating can be tricky but there are several ways to do it safely. One simple way to modify a list while iterating is by using a for loop with the index of each item. This allows us to change specific items at certain positions.
a = [1, 2, 3, 4]
for i in range(len(a)):
if a[i] % 2 == 0:
a[i] = a[i] * 2
print(a)
Output
[1, 4, 3, 8]
Let's look into other methods to Modify a List While Iterating in Python are:
Table of Content
Using List Comprehension
Create a new list based on the modifications and replace the original list if necessary. This avoids directly modifying the list during iteration.
a = [1, 2, 3, 4]
a = [x * 2 if x % 2 == 0 else x for x in a]
print(a)
Output
[1, 4, 3, 8]
Using While Loop
In some cases, we might want more control over the iteration process. Using a while loop allows us to modify the list as we go, but we need to be careful to avoid skipping elements.
a = [1, 2, 3, 4]
i = 0
while i < len(a):
if a[i] % 2 == 0:
a[i] = a[i] * 2
i += 1
print(a)
Output
[1, 4, 3, 8]
Iterating Over a Copy
Iterate over a copy of the list (list.copy()) to avoid modifying the list during iteration.
a = [1, 2, 3, 4]
for item in a.copy():
if item % 2 != 0:
a.remove(item)
print(a)
Output
[2, 4]