I recently encountered a scenario in which if a set only contained a single element, I wanted to do something with that element. To get the element, I settled on this approach:
element = list(myset)[0]
But this isn't very satisfying, as it creates an unnecessary list. It could also be done with iteration, but iteration seems unnatural as well, since there is only a single element. Am I missing something simple?
Tuple unpacking works.
(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):
1: in Python 2.5 and before, you have to use
iter(myset).next()
I suggest:
you can use
element = tuple(myset)[0]
which is a bit more efficient, or, you can do something likeI guess constructing an iterator is more efficient than constructing a tuple/list.
Between making a tuple and making an iterator, it's almost a wash, but iteration wins by a nose...:
Not sure why all the answers are using the older syntax
iter(x).next()
rather than the new onenext(iter(x))
, which seems preferable to me (and also works in Python 3.1).However, unpacking wins hands-down over both:
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:
So, unpacking for the singleton case, and
next(iter(x))
for the general case, seem best.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
ormax
. E.g.:or:
(Don't use
sorted
, because that has unnecessary overhead for this usage.)