Execute Function for Each List Element

Beginner

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.

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.