Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!news.glorb.com!feeder.erje.net!us.feeder.erje.net!news.linkpendium.com!news.linkpendium.com!panix!roy From: Roy Smith Newsgroups: comp.lang.python Subject: Re: Iterating through set Date: Mon, 14 Jul 2014 20:30:52 -0400 Organization: PANIX Public Access Internet and UNIX, NYC Lines: 26 Message-ID: References: NNTP-Posting-Host: localhost X-Trace: reader1.panix.com 1405384252 15918 127.0.0.1 (15 Jul 2014 00:30:52 GMT) X-Complaints-To: abuse@panix.com NNTP-Posting-Date: Tue, 15 Jul 2014 00:30:52 +0000 (UTC) User-Agent: MT-NewsWatcher/3.5.3b3 (Intel Mac OS X) Xref: csiph.com comp.lang.python:74451 In article , LJ wrote: > Hi All. > > I'm coding a Dynamic Programming algorithm to solve a network flow problem. > At some point in the algorithm I have to iterate through a set of nodes, > while adding and/or removing elements, until the set is empty. I know a > regular set() object does not work in a case like this, so I wonder if anyone > knows of an efficient pythonic way to handle this. You've already figured out that you can't alter a set while you're iterating over it. Which means you basically have two choices: 1) Build a new set while you're iterating over the first one, then delete the first set. This might make sense if you expect there will be a large number of items (relative to the size of the original set) added or deleted. 2) Keep lists, of those items which need adding or deleting, and do them in bulk, after the iteration is completed. Then, delete the lists. This makes sense if you expect the number of add/deletes will be small. Either way is O(n) in the size of the set, so which you pick is a second-order optimization.