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

Duncan Booth duncan.booth at invalid.invalid
Mon Apr 28 06:48:58 EDT 2014


Chris Angelico <rosuav at gmail.com> wrote:

> # 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.

Even if you have three billion keys, the extra memory needed to create a 
list that references those keys is going to be a lot less than the memory 
used by the keys themselves. For example if the keys are 6 character 
strings then each string needs I think at least 45 bytes (64 bit Python 
2.x, up to double that in Python 3.x) but the list only needs one 8 byte 
pointer per key.

I would always choose this simple solution until such time as it is proved 
to be a problem.

-- 
Duncan Booth



More information about the Python-list mailing list