[Python-talk] Stability of dict.iteritems() (etc) under deletions
Kent Johnson
kent37 at tds.net
Thu Apr 12 16:12:21 EDT 2007
Bill Freeman wrote:
> Assume that "d" is a dictionary below. Is the following safe?
>
> for k, v in d.iteritems():
> if testFunction(v):
> del d[k]
>
> or, equivalently:
>
> for k in d.iterkeys():
> if testFunction(d[k]):
> del d[k]
No, it is not safe. Commentary here:
http://mail.python.org/pipermail/python-list/2002-February/125989.html
> (I presume that the last one is equivalent to "for k in d:...".)
Yes, plus-or-minus an attribute lookup and a function call...
>
> That is, does the deletion within the loop invalidate the
> iterator, or at least can prevent it from correctly returning
> the remainder of the items (e.g.; some might not be visited, some
> already visited might be visited again)?
I don't think any Python iterators are safe this way.
>
> On the other hand, I presume that the following is safe:
>
> for k, v in d.items():
> if testFunction(d[k]):
> del d[k]
>
> - because items has returned a list object that is no longer
> tied to the dictionary by the time the first iteration runs.
Correct.
Kent
More information about the Python-talk
mailing list