Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #70643
| References | <535AA12A.1030203@earthlink.net> <mailman.9524.1398540343.18130.python-list@python.org> <535c67e9$0$29965$c3e8da3$5496439d@news.astraweb.com> |
|---|---|
| Date | 2014-04-27 12:49 +1000 |
| Subject | Re: Proper deletion of selected items during map iteration in for loop: Thanks to all |
| From | Chris Angelico <rosuav@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.9527.1398566956.18130.python-list@python.org> (permalink) |
On Sun, Apr 27, 2014 at 12:14 PM, Steven D'Aprano
<steve+comp.lang.python@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
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll 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