On Tue, Feb 18, 2014 at 04:25:28PM -0600, Ryan Gonzalez wrote:
It isn't uncommon to try and get either the first or the last True value from a list.
I'm not sure that I've ever wanted to do either. If I've ever wanted the first true value, it was so uncommon I've forgotten. But I'm pretty confident I've never wanted the *last* true value. That would be a strange thing to do.
In Python 2, you'd do this:
next((x for x in mylist if x))
That works fine in Python 3 too.
And, in Python 3, thanks to filter returning an iterator, you'd do this:
next(filter(bool,mylist))
It still is pretty common. Common enough to make it aggravating to write a function to do that nearly every time.
But you aren't writing a function. It's a simple, trivial, one-line operation, a single expression. Not every trivial one-line operation needs to be a function. Just write "next(filter(bool, mylist))" in-place, where you want it to appear. It's only a couple of characters longer than "itertools.first(mylist)", and is one less thing to memorize. [...]
Stuff that's open to lots of debate:
- Names. They're not very creative; I know. - Builtin or itertools. I'm personally leaning towards the latter at the moment.
You missed the most important question: whether or not this is worth doing at all. -- Steven