On Fri, May 22, 2020 at 8:59 PM Steven D'Aprano
Why not just this (by object, not by its index, but that seems simpler):
do_something(next(filter(pred, somelist)))
Sure, that works too. But have you ever written it for real? I haven't. And having seen it, I'll probably forget all about it within an hour.
Yes, I've written that, or something very similar for real. More than once even. But I do think in functional terms fairly easily. However, even if you don't do it that way, changing the signature on method on `list` specifically feels really clunky. What if I want to do something to the first item in a tuple that meets a condition? Or the first from a deque. Or from a set. Or even the first matching key from a dictionary. Or the first match from some third-party collection? Even if next(filter(...)) isn't how you think, an imperatively written function can be much more generic. For example (untested): def process_first(it, pred=lambda _: True, func=lambda _: _, sentinel=None): for item in it: if pred(item): return func(item) return sentinel Just stick that somewhere, and it does everything you want and more. I use a sentinel rather than raise an exception if nothing matches. That feels much more natural to me, but you can change that if such makes more sense to you. Likewise, if you want to return the "index", it's a simple enough change (but what is the index of an unsized iterable? I mean, of course you can enumerate() or i+=1... but it might not really be an index. -- The dead increasingly dominate and strangle both the living and the not-yet born. Vampiric capital and undead corporate persons abuse the lives and control the thoughts of homo faber. Ideas, once born, become abortifacients against new conceptions.