On Fri, May 22, 2020 at 08:11:16PM -0400, David Mertz wrote: > > > > After I answered that question, it dawned on me that I have probably > > written something like that loop, or variations of it, a thousand times: > > > > for obj in somelist: > > if comparison(obj, needle): > > do_something(obj) > > break > > > > 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. People who think in functional programming terms will probably love the `next(filter(...))` idiom, but not everyone thinks or likes functional programming idioms, and there are many people who would reject a patch containing that idiom. Here are some difficulties with the functional version: 1. It requires teaching people about iterators and `next` first. 2. If you want to operate on a sublist, you have to teach them about slicing, so you can introduce itertools.islice, rather than just say "give the start and end positions as arguments". 3. If you need the index instead of the value, using filter becomes downwrite obfuscated: next(filter(lambda t: pred(t[1]), enumerate(iterable)))[0] so it becomes a question of having horses for courses. We have a simple answer to a simple question: "How do I search a list?" "Use list.index" With this proposal, we get: "How do I search a list by some key?" "Use list.index with a key function" -- Steven _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/3J522Z2CG6UQZQVUZEU7DSIYXFHLYC2M/ Code of Conduct: http://python.org/psf/codeofconduct/