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

geremy condra debatem1 at gmail.com
Fri Nov 6 00:04:54 CET 2009


On Thu, Nov 5, 2009 at 4:09 PM, Alexander Belopolsky <alexander.belopolsky at gmail.com> wrote:

On Thu, Nov 5, 2009 at 3:43 PM, Chris Bergstresser <chris at subtlety.com> wrote:

.. and "x = iter(s).next()" raises a StopIteration exception. And that's why the documented recipe should probably recommend next(iter(s), default) instead.  Especially because iter(s).next() is not even valid code in 3.0.

This seems reasonably legible to you? Strikes me as coding by incantation. Also, while I've heard people say that the naive approach is slower, I'm not getting that result. Here's my test:

smrt = timeit.Timer("next(iter(s))", "s=set(range(100))") smrt.repeat(10) [1.2845709323883057, 0.60247397422790527, 0.59621405601501465, 0.59133195877075195, 0.58387589454650879, 0.56839084625244141, 0.56839680671691895, 0.56877803802490234, 0.56905913352966309, 0.56846404075622559]

naive = timeit.Timer("x=s.pop();s.add(x)", "s=set(range(100))") naive.repeat(10) [0.93139314651489258, 0.53566789627075195, 0.53674602508544922, 0.53608798980712891, 0.53634309768676758, 0.53557991981506348, 0.53578495979309082, 0.53666114807128906, 0.53576493263244629, 0.53491711616516113]

Perhaps my test is flawed in some way?

Geremy Condra



More information about the Python-Dev mailing list