Getting some element from sets.Set

Steven Bethard steven.bethard at gmail.com
Wed May 9 12:41:45 EDT 2007


tutufan at gmail.com wrote:
> I've also previously run into the same need as the original poster.  I
> no longer recall the details, but I think maybe I was implementing a
> union/find type algorithm.  This basically involves partitioning a
> universe set into partitions, where any element of a partition can be
> used as a name/handle/etc for the partition in question.  Sets are the
> obvious representation for these partitions, esp since they implement
> union efficiently.  And given this representation, it's very obvious
> to want to generate a "name" when you have a set in hand.  Since any
> element of the set serves as a name (and you know the sets are all non-
> empty), it'd be very nice to have a .element() method, or some such.
> I guess "iter(s).next()" works okay, but it's not very readable, and I
> wonder if it's efficient.

You can find out::

     $ 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().

STeVe



More information about the Python-list mailing list