The Python Oracle

Python - functional "find"?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Peaceful Mind

--

Chapters
00:00 Question
00:44 Accepted answer (Score 2)
01:39 Answer 2 (Score 3)
02:02 Answer 3 (Score 3)
02:14 Thank you

--

Full question
https://stackoverflow.com/questions/2371...

Accepted answer links:
[itertools]: http://docs.python.org/library/itertools...

Answer 3 links:
[itertools]: http://docs.python.org/library/itertools...
[ifilter]: http://docs.python.org/library/itertools...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #functionalprogramming #lambda

#avk47



ANSWER 1

Score 4


Try itertools and for example ifilter.




ANSWER 2

Score 4


I don't think there is any such function with such exact semantics, and anyway your function is short , good enough and you can easily improve it for later use, so use it.

because simple is better than complex.




ACCEPTED ANSWER

Score 2


You can use itertools.dropwhile to skip over the items for which the supplied function returns False, then take the first item of the rest (if any). If you need the index rather than the item, incorporate enumerate from the Recipes section of itertools docs.

To reverse truth values returned by the supplied function, use a lambda (lambda x: not pred (x), where pred is the supplied function) or a named wrapper:

def negate(f):
    def wrapped(x):
        return not f(x)
    return wrapped

Example:

def odd(x): return x % 2 == 1
itertools.dropwhile(negate(odd), [2,4,1]).next()
# => 1

This will throw StopIteration if no matching item is found; wrap it in a function of your own to throw an exception of your choice instead.