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

PythonSet

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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.

Solution 3 - 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.)

Solution 4 - Python

I suggest:

element = myset.pop()

Solution 5 - Python

you can use element = tuple(myset)[0] which is a bit more efficient, or, you can do something like

element = iter(myset).next()

I guess constructing an iterator is more efficient than constructing a tuple/list.

Solution 6 - Python

There is also Extended Iterable Unpacking which will work on a singleton set or a mulit-element set

element, *_ = myset

Though some bristle at the use of a throwaway variable.

Solution 7 - Python

One way is to use reduce with lambda x: x.

from functools import reduce

> reduce(lambda x: x, {3})
3

> reduce(lambda x: x, {1, 2, 3})
TypeError: <lambda>() takes 1 positional argument but 2 were given

> reduce(lambda x: x, {})
TypeError: reduce() of empty sequence with no initial value

Benefits:

  • Fails for multiple and zero values
  • Doesn't change the original set
  • Doesn't require data transformations (e.g., to list or iterable)
  • Doesn't need a new variable and can be passed as an argument
  • Arguably less awkward and PEP-compliant

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrecursiveView Question on Stackoverflow
Solution 1 - Pythonu0b34a0f6aeView Answer on Stackoverflow
Solution 2 - PythonAlex MartelliView Answer on Stackoverflow
Solution 3 - PythonCraig McQueenView Answer on Stackoverflow
Solution 4 - PythonHelmutView Answer on Stackoverflow
Solution 5 - PythonOren SView Answer on Stackoverflow
Solution 6 - PythonChrisFreemanView Answer on Stackoverflow
Solution 7 - PythonnocibambiView Answer on Stackoverflow