[Python-ideas] Function to return first(or last) true value from list

Andrew Barnert abarnert at yahoo.com
Tue Feb 18 23:37:12 CET 2014


On Feb 18, 2014, at 14:25, Ryan Gonzalez <rymg19 at gmail.com> wrote:

> 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 last functions 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.
If suggest putting it on PyPI, or submitting it to an existing project like more-itertools, and seeing what kind of uptake it has, before trying to decide whether it's necessary to add to the stdlib.

Except I think first may already be in more-itertools.
> 
> Implementing it in itertools would be simple:
> 
> def first(it):
>     return next(filter(bool,it))
> 
> def last(it):
>     return next(reversed(filter(bool,it)))
But reversed takes a sequence, not an iterator. So you'd have to call it on list(filter(...)), and surely you don't want to build the whole list just to get the last value. You could build it by using a single-element peek wrapper, or just an explicit for loop that keeps track of "last" as it goes along.


> -- 
> 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."
> 
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140218/befbf4eb/attachment.html>


More information about the Python-ideas mailing list