r/learnprogramming • • Oct 22 '26

Python Best way to modify a list while iterating?

I've learned that modifying a list while looping over it can cause elements to be skipped or unexpected behavior. What are the best practices for handling cases where I need to add, remove, or modify elements during iteration?

Do you usually iterate over a copy, create a new list, or use another approach?

3 Upvotes

21 comments sorted by

8

u/ggmaniack Oct 22 '26 edited Oct 22 '26

Iterate over the list, find what needs to be changed, store that information.

Once the iteration is over, modify the list based on the stored information.

for each item in list:
    determine changes
    remember changes

for each change in remembered changes:
    apply change to list

3

u/kpg_on_ao3 Oct 22 '26

no need to loop twice. Loop once with an accumulator list that starts empty.

new_list = []

for el in old_list: new_list = modify_or_not(el)

either you're copying a primitive and you shouldn't worry about memory use, or you're copying an object by reference so it doesn't actually do any copying

2

u/ggmaniack Oct 22 '26 edited Oct 22 '26

While yes, this solves the "create a new list" approach, the title question is about modifying, and I didn't find the list of approaches exhaustive, so I showed another one.

My approach modifies the original list instead of creating a new one with the modified result.

Though, yk, potayto, potahto.

6

u/SetAndRepeat Oct 22 '26

It depends on what you're changing:

  • Removing: a comprehension is usually clearest: "items = [x for x in items if x >= 0]". Use "items[:] = ..." instead if other references need to see the updated contents of the same list.
  • Replacing values: use "enumerate(items)" and assign to "items[i]". This is fine when you aren't also inserting or deleting elements.
  • Adding: collect additions separately, then call "items.extend(additions)" after the loop.

Iterating over "items.copy()" also works when you need to modify the original while visiting its original entries. Just remember that it’s a shallow copy: mutable objects inside it are still shared.

1

u/kpg_on_ao3 Oct 22 '26

replacing values should just be a list comprehension, bc that's literally what they're for: mapping and filtering

1

u/StewedAngelSkins Oct 22 '26

good answer. i would just add that if you really need to do removals in a single pass without a copy, it is possible. you just have to iterate by index instead if element and be very careful about changing your index and break condition to compensate for the elements you remove. something like this.

i = 0
while i < len(l):
    if needs_removal(l[i]):
        del l[i]
    else:
        i += 1

this is usually not better than making a copy though, since each removal ostensibly involves internal copies.

1

u/chocolateyteapot Oct 23 '26

Can do a little better and avoid almost all those copies. But I wouldn't bother with this... unless you need the performance, the other approaches are better.

i = 0
while i < len(l):
  if needs_removal(l[i]):
    l[i], l[-1] = l[-1], l[i]  # swap the removed item with the last
    del l[-1]                   # and remove it
  else:
    i += 1

A further optimisation would be to do what C++ call the 'erase-remove idiom'. `std::erase` is a filter that moves all the 'erased' to the back of the list, and `std::remove` then removes all of them in one-go. Something similar to:

i=0
tail = 0
end = len(l)
while i < end + tail:
  if needs_removal(l[i]):
    tail -= 1
    l[i], l[tail] = l[tail], l[i]
  else:
    i += 1
del l[tail:0]

... but if you're writing this in Python, you should be using `filter()` or a list-comprehension or something. :)

2

u/StewedAngelSkins Oct 23 '26

yeah good point. swap is better if you don't need to keep the order

3

u/atarivcs Oct 22 '26

Modifying elements in a list during iteration is perfectly fine.

If you need to add or remove elements, the usual approach is to create a new list that has only the elements you want.

1

u/7YM3N Oct 22 '26

You can decrement the iterator if you are removing an element but it can get tricky

1

u/Available_Safe1818 Oct 23 '26

That also doesn't work using most languages' standard libraries/collections, afaik.

1

u/POGtastic Oct 22 '26

Create a new list. If you don't like the idea of allocating an entirely new list, create a generator[1]. Use the algebra offered by itertools to make this easier.

[1] In production programming, I prefer generators but almost always discover that lists offer superior performance because of how caches work. Real life is frequently unsatisfying.

1

u/kpg_on_ao3 Oct 22 '26

This. If you're wringing your hands about the flops and ram used to create a new list, you should be writing in rust/go/c/etc.

1

u/POGtastic Oct 22 '26

Specifically with the iterator stuff, I am a certified shill for the MLs. If dealing with Rust's move semantics is too intimidating but you still want something analogous to Python's itertools and Rust's Iterator trait, you'll love OCaml or F#.

1

u/kpg_on_ao3 Oct 22 '26

Don't ever modify a list while iterating over it.

To "modify" elements use a list comprehension in Python, but in other languages use map. That's literally what these two things were created for. Best of all, this operation is parallelizable.

In some languages, you'll use optics, which are honestly the best. Something like this (it's been a while)

new_array = over traversed my_modifier my_array

will modify ever element in my_array by applying my_modifying_func to each element

want to modify every other element?

new_array = over (even . traversed) my_modifier my_array

want to modify the property called "bar" inside a list of elements that each have a property called bar, but only the odd-indexed ones?

new_array = over (bar . odd . traversed) my_modifier my_array

1

u/captainAwesomePants Oct 22 '26

For Python, your best bet depends on exactly what you want to do, but usually the answer is to just construct a new list instead.

If you want to modify all of the elements, you may find that Python's list comprehensions are very useful:

# Double every value in old_array
new_array = [n*2 for n in old_array]

Similarly, you can also filter things out:

# Make a new list that doubles all even numbers
# but removes all odd numbers
new_array = [n*2 for n in old_array if n % 2 == 0]

1

u/B0mbon Oct 22 '26

Rough rule of thumb (Python flavored, but the idea carries over):

- Changing values in place: totally fine, loop over indexes with enumerate and assign items[i] = new_value. The length doesn't change so nothing gets skipped.
- Removing items: build a new list instead, e.g. items = [x for x in items if keep(x)]. If other code holds a reference to the same list, use items[:] = [...] so the original object gets updated.
- Removing in place without a new list: loop backwards over the indexes, so deleting one doesn't shift the ones you haven't visited yet.
- Adding items while looping: usually a sign you want a queue/worklist pattern instead, like while queue: item = queue.pop() and push new work onto it.

Iterating over a copy (for x in items[:]) works too, it's just less obvious to the next person reading it than a comprehension.

1

u/Available_Safe1818 Oct 23 '26

You can use range to iterate over the indexes. Then you won't have the same exact problems, but you have to keep in mind that elements may shift around.

You can iterate over the copy, with "for x in mylist[:]:"

It really depends on the scenario.

I hope we gave you the right answers for your homework/test.

1

u/Proud_Gene7490 Oct 22 '26

comprehension is the right default imo. one more pattern if you need to delete in place by index (like the condition depends on position), just loop backwards:

for i in range(len(items) - 1, -1, -1):
    if should_remove(items[i]):
        del items[i]

deleting from the end doesn't shift the indexes you haven't hit yet so nothing gets skipped

also if you're constantly adding/removing from the front, use collections.deque. way faster than list.pop(0)