How to find the first element that matches your criteria in a Python list

Overview

A memo that investigated how to perform operations like ʻArray.prototype.find ()` in JavaScript in Python.

javascript find()


const fruits = ["apple", "lemon", "melon", "orange"];
const elm = fruits.find(e => e.endsWith("n"));
console.log(elm); // "lemon"

Method using filter function

The filter function takes an anonymous function described by a lambda expression as the first argument and applies it to each element of the list of second arguments. The iterator is returned by extracting the elements for which the result is true, so the result can be obtained as a list by applying the list function.

filter function


    fruits = ["apple", "lemon", "melon", "orange"]
    #filter function
    lst = list(filter(lambda x: x.endswith("n"), fruits))
    assert lst == ["lemon", "melon"]
    #filter function No matching element
    lst = list(filter(lambda x: x.endswith("x"), fruits))
    assert lst == []

If you apply the next function instead of the list function, you will get the first element that matches the condition. In the second argument of the filter function, specify None as the default value when the element is not found. (Note that without this specification, a StopIteration exception will be thrown and the system will terminate abnormally.)

filter function+find with next function


    #find by filter function
    elm = next(filter(lambda x: x.endswith("n"), fruits), None)
    assert elm == "lemon"
    #find by filter function No matching element
    elm = next(filter(lambda x: x.endswith("x"), fruits), None)
    assert elm == None

Generator type find

A generator expression is an expression that defines a generator in a notation such as list comprehension. Since a generator returns an iterator, it can be passed to the next function.

Generator type+find with next function


    #Generator type find
    elm = next((f for f in fruits if f.endswith("n")), None)
    assert elm == "lemon"
    #Find by generator expression No matching element
    elm = next((f for f in fruits if f.endswith("x")), None)
    assert elm == None

The first argument is a generator expression. The difference from the list comprehension is that it is enclosed in () instead of [].

Generator type


(f for f in fruits if f.endswith("x"))

Recommended Posts

How to find the first element that matches your criteria in a Python list
How to get the last (last) value in a list in Python
How to identify the element with the smallest number of characters in a Python list?
How to determine the existence of a selenium element in Python
How to clear tuples in a list (Python)
[Python] How to output the list values in order
How to get a list of files in the same directory with python
How to get a list of built-in exceptions in python
How to check in Python if one of the elements of a list is in another list
How to count the number of occurrences of each element in the list in Python with weight
Extract the value closest to a value from a Python list element
[Python] Programming to find the number of a in a character string that repeats a specified number of times.
How to pass the execution result of a shell command in a list in Python (non-blocking version)
How to check the memory size of a variable in Python
How to judge that the cross key is input in Python3
[Introduction to Python] How to use the in operator in a for statement?
How to check the memory size of a dictionary in Python
A script that returns 0, 1 attached to the first Python prime number
How to delete multiple specified positions (indexes) in a Python list
[Python] A program that rotates the contents of the list to the left
[Python] How to convert a 2D list to a 1D list
How to get a stacktrace in python
[Python] How to put any number of standard inputs in a list
[Introduction to Python] How to sort the contents of a list efficiently with list sort
How to format a list of dictionaries (or instances) well in Python
How to sort by specifying a column in the Python Numpy array.
How to use the C library in Python
How to embed a variable in a python string
How to create a JSON file in Python
Make a copy of the list in Python
How to notify a Discord channel in Python
How to get the files in the [Python] folder
[Python] How to draw a histogram in Matplotlib
[Python] Find the transposed matrix in a comprehension
How to remove duplicate elements in Python3 list
[Circuit x Python] How to find the transfer function of a circuit using Lcapy
[python] How to sort by the Nth Mth element of a multidimensional array
List find in Python
[Python] Solution to the problem that elements are linked when copying a list
How to retrieve the nth largest value in Python
How to get the variable name itself in python
How to get the number of digits in Python
How to know the current directory in Python in Blender
How to write a list / dictionary type of Python3
Find the part that is 575 from Wikipedia in Python
Things to note when initializing a list in Python
[Python] How to write a docstring that conforms to PEP8
[Python] How to sort dict in list and instance in list
How to use the model learned in Lobe in Python
How to execute a command using subprocess in Python
[Linux] How to put your IP in a variable
How to unit test a function containing the current time using freezegun in python
Find the difference in Python
[Python] How to use list 1
How to develop in Python
How to find the optimal number of clusters in k-means
[python] How to check if the Key exists in the dictionary
Find out the apparent width of a string in python
[Python] How to make a list of character strings character by character
How to slice a block multiple array from a multiple array in Python
How to debug the Python standard library in Visual Studio