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

Steven D'Aprano steve at pearwood.info
Sat Oct 24 00:46:48 CEST 2009

On Sat, 24 Oct 2009 06:04:12 am Terry Reedy wrote:
> John Arbash Meinel wrote:
> > So 'for x in s: break' is about 2x faster than next(iter(s)) and 3x
> > faster than (iter(s).next()).
> > I was pretty surprised that it was 30% faster than "for x in s:
> > pass". I assume it has something to do with a potential "else:"
> > statement?
> for x in s: pass
> iterates through *all* the elements in s and leaves x bound to the
> arbritrary *last* one instead of the arbitrary *first* one. For a
> large set, this would be a lot slower, not just a little.
> fwiw, I think the use case for this is sufficiently rare that it does
> not need a separate method just for this purpose.

And yet it keeps coming up, again and again... obviously people using 
sets in code think it has a use-case.

I did ask earlier for a use-case, and the OP hasn't replied, but Vitor 
Bosshard did point out one of his use-cases: he had the difference 
between two frozensets, which he knew had only one element, but due to 
the lack of pop() he had no straightforward way of finding out what 
that element was.

The lack of get() in sets and frozensets is sounding more and more to me 
like the victory of purity over practicality.

Steven D'Aprano

More information about the Python-Dev mailing list