[Python-ideas] Function to return first(or last) true value from list
Ryan Gonzalez
rymg19 at gmail.com
Tue Feb 18 23:25:28 CET 2014
It isn't uncommon to try and get either the first or the last True value
from a list. In Python 2, you'd do this:
next((x for x in mylist if x))
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. My idea is to add first and
lastfunctions that do just that.
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.
Implementing it in itertools would be simple:
def first(it):
return next(filter(bool,it))
def last(it):
return next(reversed(filter(bool,it)))
--
Ryan
If anybody ever asks me why I prefer C++ to C, my answer will be simple:
"It's becauseslejfp23(@#Q*(E*EIdc-SEGFAULT. Wait, I don't think that was
nul-terminated."
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140218/61e64dd7/attachment.html>
More information about the Python-ideas
mailing list