How to extract the member from single-member set in python?

I reckon kaizer.se's answer is great. But if your set might contain more than one element, and you want a not-so-arbitrary element, you might want to use min or max. E.g.:

element = min(myset)

or:

element = max(myset)

(Don't use sorted, because that has unnecessary overhead for this usage.)


Between making a tuple and making an iterator, it's almost a wash, but iteration wins by a nose...:

$ python2.6 -mtimeit -s'x=set([1])' 'a=tuple(x)[0]'
1000000 loops, best of 3: 0.465 usec per loop
$ python2.6 -mtimeit -s'x=set([1])' 'a=tuple(x)[0]'
1000000 loops, best of 3: 0.465 usec per loop
$ python2.6 -mtimeit -s'x=set([1])' 'a=next(iter(x))'
1000000 loops, best of 3: 0.456 usec per loop
$ python2.6 -mtimeit -s'x=set([1])' 'a=next(iter(x))'
1000000 loops, best of 3: 0.456 usec per loop

Not sure why all the answers are using the older syntax iter(x).next() rather than the new one next(iter(x)), which seems preferable to me (and also works in Python 3.1).

However, unpacking wins hands-down over both:

$ python2.6 -mtimeit -s'x=set([1])' 'a,=x'
10000000 loops, best of 3: 0.174 usec per loop
$ python2.6 -mtimeit -s'x=set([1])' 'a,=x'
10000000 loops, best of 3: 0.174 usec per loop

This of course is for single-item sets (where the latter form, as others mentioned, has the advantage of failing fast if the set you "knew" had just one item actually had several). For sets with arbitrary N > 1 items, the tuple slows down, the iter doesn't:

$ python2.6 -mtimeit -s'x=set(range(99))' 'a=next(iter(x))'
1000000 loops, best of 3: 0.417 usec per loop
$ python2.6 -mtimeit -s'x=set(range(99))' 'a=tuple(x)[0]'
100000 loops, best of 3: 3.12 usec per loop

So, unpacking for the singleton case, and next(iter(x)) for the general case, seem best.


Tuple unpacking works.

(element,) = myset

(By the way, python-dev has explored but rejected the addition of myset.get() to return an arbitrary element from a set. Discussion here, Guido van Rossum answers 1 and 2.)

My personal favorite for getting an arbitrary element is (when you have an unknown number, but also works if you have just one):

element = next(iter(myset)) ¹

1: in Python 2.5 and before, you have to use iter(myset).next()


I suggest:

element = myset.pop()

Tags:

Python

Set