As everyone else explained, you cannot change the list, iterate over it.
You can change the list, iterate over its copy, but it's probably best to just create a new filtered list:
di = {"a": 3, "children": [{"b": 5}, {"c": 6}]} di['children'] = [el for el in di['children'] if el not in di['children']]
Why is it better? Well, that means you avoid mutating the list, which makes your code easier to reason about, easier to track, usually easier to write, and often faster and more economical. The fact that you donβt have to worry about problems with mutation and repetition is a great example of the easier to reason part.
In some cases, it becomes harder to write, or slower, or less economical, so this is just a guideline, not a hard rule. But itβs always, at least, worth considering: βCan I rewrite this as an immutable filter instead of a mutator,β even if the answer may sometimes be βno.β
And really, isn't your algorithm guaranteed to be equivalent to simply emptying everything? In this case:
di = {"a": 3, "children": [{"b": 5}, {"c": 6}]} di['children'] = []
source share