
[Guido]
def first(it, /, default=None): it = iter(it) try: return next(it) except StopIteration: return default
[Greg Ewing <greg.ewing@canterbury.ac.nz>]
Can you provide any insight into why you think it's better for it never to raise an exception, as opposed to raising something other than StopIteration when the iterator is empty and no default is specified?
Worth pursuing. As Wes Turner's post just reminded me, the more-itertools `first()` raises an exception (ValueError) when the iterable argument is exhausted and a default is not supplied. And I think that's The Rightest Thing, for reasons you explained (repeated here for completeness, with no new comments from me, beyond that #2 is my most common use case):"
There seem to be two kinds of use case for this:
1. The iterator may or may not be empty, and you don't want the hassle of having to catch an exception.
2. You expect the iterator to never be empty; if it is, then it's a bug, and you would like to get an exception, but not StopIteration because that can mess other things up.
Your version of the function seems to be aimed exclusively at case 1. If it were to raise ValueError on an empty iterable unless a default were explicitly given, it would address both cases.