Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why remove element of deque Fail?

Tags:

python

deque

I run code as follow:

q = deque([4,5,6,7,8])
for e in q:
    print("remove the {0}".format(e))
    q.remove(e)

Traceback (most recent call last):
  File "C:\Program Files\Python365\lib\site-packages\IPython\core\interactiveshell.py", line 2963, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-18-63a1d575cfeb>", line 1, in <module>
    for e in q:
RuntimeError: deque mutated during iteration
remove the 4

why raise the RuntimeError?

like image 226
Sigma65535 Avatar asked Nov 29 '25 15:11

Sigma65535


1 Answers

You can't modify a deque while iterating over it.

A typical pattern with queues is to use a while loop instead, and remove items from the desired end, with deque.pop() or deque.popleft().

E.g.:

>>> q = deque([4,5,6,7,8])
>>> while q:
...     element = q.pop()
...     print('removed {}'.format(element))
...
removed 8
removed 7
removed 6
removed 5
removed 4

or:

>>> q = deque([4,5,6,7,8])
>>> while q:
...     element = q.popleft()
...     print('removed {}'.format(element))
...
removed 4
removed 5
removed 6
removed 7
removed 8
like image 83
fferri Avatar answered Dec 02 '25 05:12

fferri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!