Proper deletion of selected items during map iteration in for loop: Thanks to all

Chris Angelico rosuav at gmail.com
Sat Apr 26 22:49:08 EDT 2014


On Sun, Apr 27, 2014 at 12:14 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> I think the two obviously good enough approaches are:
>
> - save a "to be deleted" list, then delete those keys;
>
> - copy the "not to be deleted" items into a new dict

For a small enough dict that the performance question doesn't matter,
I'd go with the other option: iterate over a snapshot of the keys.
Compare:

# Naive approach:
for k in d:
    if f(k): del d[k]

# Snapshot of keys:
for k in list(d):
    if f(k): del d[k]

No extra loop at the end, no switching out and in of contents, just
one little change in the loop header. Obviously you don't want to do
this when you're deleting two out of three billion, but for smallish
dicts, that won't make a visible change.

ChrisA



More information about the Python-list mailing list