Why is it not safe to modify sequence being iterated on?

Without getting too technical:

If you’re iterating through a mutable sequence in Python and the sequence is changed while it’s being iterated through, it is not always entirely clear what will happen. If you insert an element in the sequence while iterating through it, what would now reasonably be considered the “next” element in the sequence? What if you delete the next object?

For this reason, iterating through a mutable sequence while you’re changing it leads to unspecified behaviour. Anything might happen, depending on exactly how the list is implemented. 🙂

Leave a Comment