List find in Python

A function that scans an iterator and returns the first value that matches the condition (Corresponding to Javascript or Ruby find)

See the official Python itertools recipe http://docs.python.jp/3/library/itertools.html

python


def first_true(iterable, default=False, pred=None):
    """Returns the first true value in the iterable.

    If no true value is found, returns *default*

    If *pred* is not None, returns the first item
    for which pred(item) is true.

    """
    # first_true([a,b,c], x) --> a or b or c or x
    # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
    return next(filter(pred, iterable), default)

Recommended Posts

List find in Python
Sorted list in Python
Filter List in Python
Find the difference in Python
Find permutations / combinations in Python
[Python] list
Getting list elements in Python
Let's find pi in Python
Difference between list () and [] in Python
[python] Manage functions in a list
Output 2017 Premium Friday list in Python
Delete multiple elements in python list
Quadtree in Python --2
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Python basics: list
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Unittest in python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
Python> Comprehension / Comprehension> List comprehension
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
Python list manipulation
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
Find files like find on linux in Python
Display a list of alphabets in Python 3
Download images from URL list in Python
Find and check inverse matrix in Python
Find (deterministic finite) Cartesian automata in Python