I have a deque in Python that I'm iterating over. Sometimes the deque changes while I'm interating which produces a RuntimeError: deque mutated during iteration
.
If this were a Python list instead of a deque, I would just iterate over a copy of the list (via a slice like my_list[:]
, but since slice operations can't be used on deques, I wonder what the most pythonic way of handling this is?
My solution is to import the copy module and then iterate over a copy, like for item in copy(my_deque):
which is fine, but since I searched high and low for this topic I figured I'd post here to ask?
You can directly iterate over the deque.
The iterator() method of Deque Interface returns an iterator over the elements in this deque in a proper sequence. The elements will be returned in order from first (head) to last (tail). The returned iterator is a “weakly consistent” iterator.
Practical Data Science using Python A double-ended queue, or deque, has the feature of adding and removing elements from either end. The Deque module is a part of collections library. It has the methods for adding and removing elements which can be invoked directly with arguments.
You can "freeze" it by creating a list. There's no necessity to copy it to a new deque. A list is certainly good enough, since you only need it for iterating.
for elem in list(my_deque):
...
list(x)
creates a list from any iterable x
, including deque, and in most cases is the most pythonic way to do so.
Bare in mind this solution is only valid if the deque is being modified in the same thread (i.e. inside the loop). Else, be aware that list(my_deque)
is not atomic, and is also iterating over the deque. This means that if another thread alters the deque while it runs, you end up with the same error. If you're in a multithreaded environment, use a lock.
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