Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #70674

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

From Duncan Booth <duncan.booth@invalid.invalid>
Newsgroups comp.lang.python
Subject Re: Proper deletion of selected items during map iteration in for loop: Thanks to all
Date 2014-04-28 10:48 +0000
Message-ID <XnsA31D7830AB42Cduncanbooth@127.0.0.1> (permalink)
References <535AA12A.1030203@earthlink.net> <mailman.9524.1398540343.18130.python-list@python.org> <535c67e9$0$29965$c3e8da3$5496439d@news.astraweb.com> <mailman.9527.1398566956.18130.python-list@python.org>

Show all headers | View raw


Chris Angelico <rosuav@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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Re: Proper deletion of selected items during map iteration in for loop: Thanks to all Charles Hixson <charleshixsn@earthlink.net> - 2014-04-26 12:25 -0700
  Re: Proper deletion of selected items during map iteration in for loop: Thanks to all Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-04-27 02:14 +0000
    Re: Proper deletion of selected items during map iteration in for loop: Thanks to all Chris Angelico <rosuav@gmail.com> - 2014-04-27 12:49 +1000
      Re: Proper deletion of selected items during map iteration in for loop: Thanks to all Duncan Booth <duncan.booth@invalid.invalid> - 2014-04-28 10:48 +0000
    Re: Proper deletion of selected items during map iteration in for loop: Thanks to all Roy Smith <roy@panix.com> - 2014-04-26 22:57 -0400

csiph-web