It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate over a copy. The slice notation makes this particularly convenient:
>>> for x in a[:]: # make a slice copy of the entire list ... if len(x) > 6: a.insert(0, x) ... >>> a ['defenestrate', 'cat', 'window', 'defenestrate']
why is it not safe to just do for x in a
??
One big reason for not allowing modification of a collection while iterating on it is that, if elements in the collection are deleted or if new elements are inserted, it will throw the iteration off. (An element was inserted or deleted right where the iteration is working in the collection; what's the next element now?
Because you iterate over a copy of the list, you can modify the original list without damaging the iterator.
a : a procedure in which repetition of a sequence of operations yields results successively closer to a desired result.
You cannot access items in a set by referring to an index, since sets are unordered the items has no index. But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.
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. :-)
This is a common problem in many languages. If you have a linear data structure, and you are iterating over it, something must keep track of where you are in the structure. It might be a current index, or a pointer, but it's some kind of finger pointing to the "current place".
If you modify the list while the iteration is happening, that cursor will likely be incorrect.
A common problem is that you remove the item under the cursor, everything slides down one, the next iteration of the loop increments the cursor, and you've inadvertently skipped an item.
Some data structure implementations offer the ability to delete items while iterating, but most do not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With