For ideas like this it is best to discuss them on python-ideas.

I'll also mention that this idea has been brought up at least twice before: search for threads about itertools and single() or first() (if I remember correctly).

On Mon, Jul 27, 2020 at 12:07 PM Noam Yorav-Raphael <> wrote:

There's a simple function that I use many times, and I think may be a good fit to be added to itertools. A function that gets an iterator, and if it has exactly one element returns it, and otherwise raises an exception. This is very useful for cases where I do some sort of query that I expect to get exactly one result, and I want an exception to be raised if I'm wrong. For example:

jack = one(p for p in people if == '1234')

sqlalchemy already has such a function for queries:

This is my implementation:

def one(iterable):
    it = iter(iterable)
        r = next(it)
    except StopIteration:
        raise ValueError("Iterator is empty")
    except StopIteration:
        return r
        raise ValueError("Iterator has more than one item")

What do you think?

Python-Dev mailing list --
To unsubscribe send an email to
Message archived at
Code of Conduct: