Best way to extract an item from a set of len 1

Alex Martelli aleax at mail.comcast.net
Wed Jan 25 10:35:35 EST 2006


Fredrik Lundh <fredrik at pythonware.com> wrote:
   ...
> the obvious solution is
> 
>     item = list(s)[0]
> 
> but that seems to be nearly twice as slow as [x for x in s][0]
> under 2.4.  hmm. 

Funny, and true on my laptop too:

helen:~ alex$ python -mtimeit -s's=set([23])' 'x=list(s)[0]'
100000 loops, best of 3: 2.55 usec per loop
helen:~ alex$ python -mtimeit -s's=set([23])' 'x=[x for x in s][0]'
100000 loops, best of 3: 1.48 usec per loop
helen:~ alex$ python -mtimeit -s's=set([23])' '[x for x in s]'
1000000 loops, best of 3: 1.36 usec per loop

Exploiting the design defect whereby a LC leaves variables bound can
shave another few percents off it, as shown.

> here's a faster variant:
> 
>     item = iter(s).next()

Not all that fast here:

helen:~ alex$ python -mtimeit -s's=set([23])' 'x=iter(s).next()'
100000 loops, best of 3: 1.71 usec per loop

> but at least on my machine, your two-step solution
> 
>     item = s.pop(); s.add(item)
> seems to be even faster.

Not really, here:

helen:~ alex$ python -mtimeit -s's=set([23])' 'x=s.pop();s.add(x)'
100000 loops, best of 3: 1.49 usec per loop

No joy from several variations on transform-and-pop:

helen:~ alex$ python -mtimeit -s's=set([23])' 'x=set(s).pop()'    
100000 loops, best of 3: 2.21 usec per loop
helen:~ alex$ python -mtimeit -s's=set([23])' 'x=list(s).pop()'
100000 loops, best of 3: 3.2 usec per loop
helen:~ alex$ python -mtimeit -s's=set([23])' 'x=tuple(s)[0]'
100000 loops, best of 3: 1.79 usec per loop


Fastest I've found is unpacking-assignment:

helen:~ alex$ python -mtimeit -s's=set([23])' 'x,=s'          
1000000 loops, best of 3: 0.664 usec per loop


Alex



More information about the Python-list mailing list