Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

13
  • 8
    If you are wrapping it with a method, at least catch StopIteration and raise EmptySequence error. Would be much prettier when there are no elements.
    – Guy
    Commented Jan 26, 2018 at 3:28
  • 3
    @guyarad StopIteration is the canonical "out of elements" exception in python. I don't see a problem with it being thrown. I'd probably use a default of "None" which can be passed in as a default parameter to the function.
    – Baldrickk
    Commented May 24, 2018 at 7:51
  • 2
    Baldrickk I feel like this isn't an iteration method. You won't call this one in a contest of an iterator. But I'm not feeling too strongly about it :)
    – Guy
    Commented May 25, 2018 at 12:45
  • 1
    There should be an optional default argument, and if that argument not be supplied, only then raise an exception when no element in the sequence satisfy the condition.
    – Zorf
    Commented Feb 26, 2020 at 22:39
  • 1
    Yep! The other thing you'll want to do here is test whether condition exists before trying to write a condition; sometimes even returning x at all from an iterator could be expensive (e.g., if x is a generator yield). So check if condition otherwise just return next(x for x in iterable, default) Commented Apr 11, 2021 at 23:31