简体   繁体   中英

Python list can be mutated during iteration but not deque. Why?

I need to identify elements in data structure meet a condition, save them somewhere and finally remove from the original structure. Consequently, I use for cycle instead of comprehension.

When trying to reimplement the process with deque, I get the following error: RuntimeError: deque mutated during iteration.

from collections import deque

def foo1(x):
    pass

myDeque = deque([i for i in range(200)])  # i is in fact a complex, nested data structure

for index, e in enumerate(reversed(myDeque)):
    if e % 2 == 0: # also more complex logic
        foo1(e)
        # myDeque.pop(index) # TypeError: pop() takes no arguments (1 given)
        del myDeque[index] # RuntimeError: deque mutated during iteration
    

Why can I mutate list during iteration but not deque? Append / insert works in both.

I currently work around with a temporary list built from deque.

from collections import deque

def foo1(x):
    pass

myDeque = deque([i for i in range(200)])

temp = list(myDeque)
for index, e in enumerate(reversed(temp)):
    if e % 2 == 0:
        foo1(e)
        temp.pop(index - 1)
myDeque = deque(temp)

Workaround: create a temp list

from collections import deque

def foo1(x):
    pass

myDeque = deque([i for i in range(200)])

temp = list(myDeque)
for index, e in enumerate(reversed(temp)):
    if e % 2 == 0:
        foo1(e)
        temp.pop(index - 1)
myDeque = deque(temp)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM