> > if comparison(obj, needle):
> > do_something(obj)
> > break
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.
I wouldn't reject it, but I don't love the functional idioms (well, I don't love the functional functions (map, filter, vs comprehensions) -- I'd be inclined to go the comprehension way -- which woukld only require understanding next() if you only wanted the first one, but I suspect most of the time you don't only want the first anyway.
1. It requires teaching people about iterators and `next` first.
Interesting -- in other recent threads, Ive felt that those of us that thought "iterators and `next" were relatively advanced concepts that newbies didn't need to learn were dismissed ...
But in this case:
next(i for i in a_list if pred(i))
doesn't really require the full concept of iterators and iterables -- it requires comprehension syntax, and a quick "next() gives you the next item in an 'iterator' and an 'iterator' is something you can put in a for loop." -- yes, that leaves out all kinds of important details, but gets the job done for now.
In fact, in my intro class, I've used "how to get the first item from a thing" as my first introduction to next() :-)
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".
hmm -- a great reason to provide an easily accessible "lazy" slice -- like the sequence view proposal recently discussed (and waiting for me to flesh out ...)
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]
indeed. but how often DO people need the index? I suspect many uses of .index() are used to then get the object anyway. And I'm not sure it's THAT obfuscated -- we teach folks to use enumerate() pretty early as a way to avoid explicitly looping through indexes.
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"
Interestingly, this seems to contradict API design-wise, what's been pushed on recent threads:
* Rather than adding a keyword argument that changes behavior, we should add another function to itertools (or the like)
and
* rather than add functionality to a built-in (or ABC), we should add utility functions that can act on many related types
Granted, this is not a flag (neither boolean, ternary or mode-switching), and it's not a new method, but the API principles may still apply. In particular, a function in itertools would have a lot more utility for various iterables, rather than just lists (or the /sequence ABC?)
-CHB