Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a built-in equivalent to C#'s Enumerable.Single()?

Tags:

python

in C#, if you have an enumerable and try to call .Single() on it, it will throw an error if it does not have exactly one element in it.

Is there something similar built-in to Python for this?

if len(iterable) == 0 or len(iterable) > 1:
    raise Error("...")
return iterable[0]
like image 778
neverendingqs Avatar asked Dec 04 '22 01:12

neverendingqs


1 Answers

Not a built in method, but there is an idiomatic way to achieve the same goal:

(value,) = iterable raises ValueError if iterable doesn't contain exactly one element.

The single element will be stored in value so your example could be simplified to:

(value,) = iterable
return value

The unpacking is a feature of the assignment operator.

If the target list is a comma-separated list of targets: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

like image 99
Alexander Holmbäck Avatar answered Dec 06 '22 14:12

Alexander Holmbäck