[Python-Dev] Retrieve an arbitrary element from a set without removing it

John Arbash Meinel john at arbash-meinel.com
Mon Oct 26 03:20:51 CET 2009

Hash: SHA1

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
[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.

Version: GnuPG v1.4.9 (Cygwin)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/


More information about the Python-Dev mailing list