Set & Frozenset?

Lie Ryan lie.1296 at gmail.com
Tue Mar 10 10:30:25 EDT 2009


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?

Note: the second one exhausts the iter object.



More information about the Python-list mailing list