Test if every list element is truthy

PythonPythonBeginner
Practice Now

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

Introduction

In Python, we can use the all() function to check if all elements in a list are truthy. However, sometimes we may want to check if a specific condition is true for every element in the list. In this challenge, you will need to create a function that checks if a provided function returns True for every 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-13627{{"`Test if every list element is truthy`"}} python/booleans -.-> lab-13627{{"`Test if every list element is truthy`"}} python/lists -.-> lab-13627{{"`Test if every list element is truthy`"}} python/tuples -.-> lab-13627{{"`Test if every list element is truthy`"}} python/function_definition -.-> lab-13627{{"`Test if every list element is truthy`"}} python/default_arguments -.-> lab-13627{{"`Test if every list element is truthy`"}} python/lambda_functions -.-> lab-13627{{"`Test if every list element is truthy`"}} python/build_in_functions -.-> lab-13627{{"`Test if every list element is truthy`"}} end

Test if every list element is truthy

Write a function called every(lst, fn = lambda x: x) that takes a list lst and a function fn as arguments. The function should return True if fn returns True for every element in the list, and False otherwise. If no function is provided, the function should use the identity function (lambda x: x) by default.

To solve this problem, you will need to use the all() function in combination with map() and the provided function fn to check if fn returns True for all elements in the list.

def every(lst, fn = lambda x: x):
  return all(map(fn, lst))
every([4, 2, 3], lambda x: x > 1) ## True
every([1, 2, 3]) ## True

Summary

In this challenge, you have learned how to create a function that checks if a provided function returns True for every element in a list. You have used the all() function in combination with map() and the provided function to solve the problem.

Other Python Tutorials you may like