Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a built-in Python function which will return the first True-ish value when mapping a function over an iterable?

Tags:

python

Here's the functionality I mean, and I do it pretty frequently so maybe I'm just reimplementing a built-in that I haven't seen:

import itertools
def first(fn, *args):
    for x in itertools.chain(*args):
        value = fn(x)
        if value: return value

# Example use:
example = {'answer': 42, 'bring': 'towel'}
print first(example.get, ['dolphin', 'guide', 'answer', 'panic', 'bring'])
# Prints 42

Does Python let me do this with built-ins?

like image 353
Blixt Avatar asked May 19 '15 16:05

Blixt


2 Answers

You essentially want to map example.get on the sequence, and get the first true-ish value. For that, you can use filter with the default filter function that does exactly that, and get the first of that using next:

>>> example = {'answer': 42, 'bring': 'towel'}
>>> lst = ['dolphin', 'guide', 'answer', 'panic', 'bring']
>>> next(filter(None, map(example.get, lst)))
42

In Python 3, all these things are lazy, so the whole sequence isn’t iterated. In Python 2, you can use itertools to get the lazy versions of the builtins, imap and ifilter

like image 91
poke Avatar answered Oct 01 '22 14:10

poke


you can use next() builtin and generator expression:

next(example[key] 
        for key in ['dolphin', 'guide', 'answer', 'panic', 'bring'] 
        if key in example)

if you want to use predefined function, it might be better to use filter, which accepts function as the first argument (lambda in example):

next(itertools.ifilter(lambda txt: 'a' in txt, ['foo', 'bar']))
like image 32
m.wasowski Avatar answered Oct 01 '22 14:10

m.wasowski