Find Matching Value

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In Python, we can use a list comprehension and next() to find the value of the first element in a given list that satisfies a provided testing function. This can be useful in many scenarios, such as finding the first odd number in a list or the first string that starts with a certain letter.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/AdvancedTopicsGroup(["`Advanced Topics`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/lambda_functions("`Lambda Functions`") python/AdvancedTopicsGroup -.-> python/iterators("`Iterators`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13640{{"`Find Matching Value`"}} python/conditional_statements -.-> lab-13640{{"`Find Matching Value`"}} python/for_loops -.-> lab-13640{{"`Find Matching Value`"}} python/lists -.-> lab-13640{{"`Find Matching Value`"}} python/tuples -.-> lab-13640{{"`Find Matching Value`"}} python/function_definition -.-> lab-13640{{"`Find Matching Value`"}} python/lambda_functions -.-> lab-13640{{"`Find Matching Value`"}} python/iterators -.-> lab-13640{{"`Find Matching Value`"}} python/build_in_functions -.-> lab-13640{{"`Find Matching Value`"}} end

Find Matching Value

Write a function called find(lst, fn) that takes a list lst and a testing function fn as arguments. The function should return the value of the first element in lst for which fn returns True. If no element satisfies the testing function, the function should return None.

def find(lst, fn):
  return next(x for x in lst if fn(x))
find([1, 2, 3, 4], lambda n: n % 2 == 1) ## 1

Summary

In this challenge, you learned how to find the value of the first element in a list that satisfies a provided testing function using a list comprehension and next(). This technique can be useful in many scenarios and can help you write more efficient and concise code.

Other Python Tutorials you may like