mutating a deque whilst iterating over it

dn PythonList at DancesWithMice.info
Thu Feb 11 16:17:31 EST 2021


On 12/02/2021 09.22, duncan smith wrote:
> Hello,
>       It seems that I can mutate a deque while iterating over it if I
> assign to an index, but not if I append to it. Is this the intended
> behaviour? It seems a bit inconsistent. Cheers.


Yes, and no! Agree and disagree. (see how decisive I can be?)

Inconsistent when compared with what?


A tuple is immutable, but if it contains mutable objects as elements,
they are mutable. Consistent!


That said, tuples can't be append-ed/extend-ed, so a deque may seem more
like a list than a tuple. A list will allow both element and list mutation.

Substituting a list in the sample code, the iterator will adjust to
include an appended element. Inconsistent!


However... what happens if you have a for-loop which processes a list,
and within the loop one element is mutated in value and another appended
to the list?

Oops!


Maybe the deque authors wanted to avoid that, or perhaps such is related
to the option to bound the length of a deque (by design or side-effect)?
Imagine a bounded-deque (completely 'filled') and the code is
(overly-simple example) printing its contents. If the deque-element
printing-loop also allows deque-mutation, then the first value(s),
previously printed, will no longer exist within the queue.


I'm enjoying the question: wither inconsistency? Perhaps someone (wiser)
will jump in...
-- 
Regards,
=dn


More information about the Python-list mailing list