can't delete from a dictionary in a loop

Terry Reedy tjreedy at udel.edu
Fri May 16 19:46:52 EDT 2008


"Dan Upton" <upton at virginia.edu> wrote in message 
news:5504f9ac0805161422r31f3a0d6sbe4e49914ade7383 at mail.gmail.com...
| RuntimeError: dictionary changed size during iteration

If you do not actually need a dict, an explicitly managed list is an 
[untested]alternative.

maxproc = #
procs = []
while True:
  if len(procs) < maxproc: [populate procs up to maxproc]
  i, nprocs = 0, len(procs)
  if not nprocs: break
  while i < nprocs:
    if terminated(procs[i]):
      del procs[i]
      nprocs -= 1
    else:
       i += 1

I am assuming that maxproc is low enough that the O(n) behavior of deletion 
is inconsequential.

tjr






More information about the Python-list mailing list