Getting some element from sets.Set

Raymond Hettinger python at rcn.com
Fri Jun 29 04:44:28 EDT 2007


>      $ python -m timeit -s "s = set('abcdef')" "x = iter(s).next()"
>      1000000 loops, best of 3: 0.399 usec per loop
>
>      $ python -m timeit -s "s = set('abcdef')" "x = s.pop(); s.add(x)"
>      1000000 loops, best of 3: 0.339 usec per loop
>
> So it looks like it's more efficient to use s.pop() + s.add().


There's a faster, cleaner way:

>python -m timeit -s "s = set('abcdef')" "x = iter(s).next()"
1000000 loops, best of 3: 0.539 usec per loop

>python -m timeit -s "s = set('abcdef')" "x = s.pop(); s.add(x)"
1000000 loops, best of 3: 0.465 usec per loop

>python -m timeit -s "s = set('abcdef')" "for x in s: break"
1000000 loops, best of 3: 0.175 usec per loop


FWIW, the latter approach is general purpose and works with any
iterable (useful for reading the first line of file objects for
example).


Raymond




More information about the Python-list mailing list