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

Viewed 38255

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?

7 Answers

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

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.

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
Related