[Python-ideas] Add single() to itertools
Joao S. O. Bueno
jsbueno at python.org.br
Tue Oct 31 08:42:23 EDT 2017
When I need something like this, I usually rop a line on the module
namespace that goes like:
first = lambda x: next(iter(x))
On 30 October 2017 at 23:09, Steven D'Aprano <steve at pearwood.info> wrote:
> On Tue, Oct 31, 2017 at 07:51:02AM +1100, Cameron Simpson wrote:
>> return the(nodes)
>> It's this kind of thing that expresses my intent better than the:
>> node, = nodes
>> return node
> If the intent is to indicate that there is only one node, then
> "the(nodes)" fails completely. "The" can refer to plurals as easily as
> "Wash the dirty clothes."
> (Later) "Why did you only wash one sock?"
> The simplest implementation of this "single()" function I can think of
> would be:
> def single(iterable):
> result, = iterable
> return result
> That raises ValueError if iterable has too few or too many items, which
> I believe is the right exception to use. Conceptually, there's no
> indexing involved, so IndexError would be the wrong exception to use.
> We're expecting a compound value (an iterable) with exactly one item. If
> there's not exactly one item, that's a ValueError.
> Python-ideas mailing list
> Python-ideas at python.org
> Code of Conduct: http://python.org/psf/codeofconduct/
More information about the Python-ideas