Search code examples
pythondeque

why remove element of deque Fail?


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?


Solution

  • 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