[Python-Dev] Retrieve an arbitrary element from a set without removing it (original) (raw)

geremy condra debatem1 at gmail.com
Mon Oct 26 03:46:31 CET 2009


Martin v. Löwis wrote:

Hmm, perhaps when using sets as work queues?

A number of comments: - it's somewhat confusing to use a set as a queue, given that it won't provide FIFO semantics. - there are more appropriate and direct container structures available, including a dedicated Queue module (even though this might be doing to much with its thread-safety). - if you absolutely want to use a set as a work queue, then the .pop() method should be sufficient, right? Regards, Martin We were using sets to track the tips of a graph, and to compare whether one node was an ancestor of another one. We were caching that answer into frozensets, since that made them immutable. If res = heads(node1, node2) if len(res) == 1:  # What is the 'obvious' way to get the node out? I posit that there isn't an obvious way to get the single item out of a 1-entry frozenset. for x in res: break list(res)[0] set(res).pop() iter(res).next() [x for x in res][0] x, = res   # I didn't think of this one before recently Are all answers, but none of them I would consider obvious. At the least, none of them are obviously better than another, so you look into the performance characteristics to give you a reason to pick one over the other. res.get() would be a fairly obvious way to do it. Enough that I would probably never have gone searching for any of the other answers. Though personally, I think I would call it "set.peek()", but the specific name doesn't really matter to me. John

When I first wrote Graphine (graph library), I did something very similar to the last solution. The code has since been rewritten to avoid the issue, but it would be nice if it didn't have to be the next time it comes up- the comma is easy to miss, and while the results are common-sense once you get what the line is doing, it doesn't lend itself to immediate comprehension.

Geremy Condra



More information about the Python-Dev mailing list