Execute Function for Each List Element

PythonPythonBeginner
Practice Now

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

Introduction

In Python, it is common to need to execute a function for each element in a list. This can be done using a for loop, but it can be tedious to write out the loop every time. In this challenge, you will create a function that takes a list and a function as arguments and executes the function for each element in the list.


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/BasicConceptsGroup -.-> python/comments("`Comments`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") subgraph Lab Skills python/comments -.-> lab-13643{{"`Execute Function for Each List Element`"}} python/for_loops -.-> lab-13643{{"`Execute Function for Each List Element`"}} python/lists -.-> lab-13643{{"`Execute Function for Each List Element`"}} python/tuples -.-> lab-13643{{"`Execute Function for Each List Element`"}} python/function_definition -.-> lab-13643{{"`Execute Function for Each List Element`"}} end

Execute Function for Each List Element

Write a function for_each(itr, fn) that takes a list itr and a function fn as arguments. The function should execute fn once for each element in itr.

def for_each(itr, fn):
  for el in itr:
    fn(el)
for_each([1, 2, 3], print) ## 1 2 3

Summary

In this challenge, you created a function that takes a list and a function as arguments and executes the function for each element in the list. This is a useful technique for applying a function to every element in a list without having to write out a for loop every time.

Other Python Tutorials you may like