Test if some list elements are truthy

PythonPythonBeginner
Practice Now

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

Introduction

In Python, we can use the any() function to check if at least one element in a list is True. In this challenge, you will need to create a function that takes a list and a function as arguments, and returns True if the function returns True for at least one element in the list.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/default_arguments("`Default Arguments`") python/FunctionsGroup -.-> python/lambda_functions("`Lambda Functions`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13717{{"`Test if some list elements are truthy`"}} python/booleans -.-> lab-13717{{"`Test if some list elements are truthy`"}} python/lists -.-> lab-13717{{"`Test if some list elements are truthy`"}} python/tuples -.-> lab-13717{{"`Test if some list elements are truthy`"}} python/function_definition -.-> lab-13717{{"`Test if some list elements are truthy`"}} python/default_arguments -.-> lab-13717{{"`Test if some list elements are truthy`"}} python/lambda_functions -.-> lab-13717{{"`Test if some list elements are truthy`"}} python/build_in_functions -.-> lab-13717{{"`Test if some list elements are truthy`"}} end

Test if some list elements are truthy

Write a function some(lst, fn) that takes a list lst and a function fn as arguments. The function should return True if the function fn returns True for at least one element in the list lst. If no element in the list satisfies the condition, the function should return False. If no function is provided, the function should use the identity function (which returns the element itself).

def some(lst, fn = lambda x: x):
  return any(map(fn, lst))
some([0, 1, 2, 0], lambda x: x >= 2 ) ## True
some([0, 0, 1, 0]) ## True

Summary

In this challenge, you learned how to use the any() function in combination with map() to check if a function returns True for at least one element in a list. You also created a function that takes a list and a function as arguments, and returns True if the function returns True for at least one element in the list.

Other Python Tutorials you may like