Set & Frozenset?

R. David Murray rdmurray at bitdance.com
Tue Mar 10 20:03:51 EDT 2009


Lie Ryan <lie.1296 at gmail.com> wrote:
> Matt Nordhoff wrote:
> > Alan G Isaac wrote:
> >>> Hans Larsen schrieb:
> >>>>             How could I "take" an elemment from a set or a frozenset 
> >>
> >> On 3/8/2009 2:06 PM Diez B. Roggisch apparently wrote:
> >>> You iterate over them. If you only want one value, use
> >>> iter(the_set).next()
> >>
> >> I recall a claim that
> >>
> >>     for result in myset: break
> >>
> >> is the most efficient way to get one result.
> >> Is this right? (It seems nearly the same.)
> >>
> >> Alan Isaac
> > 
> > Checking Python 2.5 on Linux, your solution is much faster, but seeing
> > as they both come in under a microsecond, it hardly matters.
> 
> 
> It's unexpected...
> 
>  >>> timeit.timeit('res=iter(myset).next()', 'myset=range(1000000)')
> 0.88944123999999647
>  >>> timeit.timeit('res=myset.next()', 'myset=range(1000000); 
> myset=iter(myset)')
> 0.49165520000002516
>  >>> timeit.timeit('for res in myset: break', 'myset=range(1000000)')
> 0.32933007999997699
> 
> I'd never expect that for-loop assignment is even faster than a 
> precreated iter object (the second test)... but I don't think this 
> for-looping variable leaking behavior is guaranteed, isn't it?

My guess would be that what's controlling the timing here is
name lookup.  Three in the first example, two in the second,
and one in the third.

--
R. David Murray           http://www.bitdance.com




More information about the Python-list mailing list