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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With