Execute Function for Each List Element | Challenge

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`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13111{{"`Execute Function for Each List Element | Challenge`"}} python/for_loops -.-> lab-13111{{"`Execute Function for Each List Element | Challenge`"}} python/lists -.-> lab-13111{{"`Execute Function for Each List Element | Challenge`"}} python/tuples -.-> lab-13111{{"`Execute Function for Each List Element | Challenge`"}} python/function_definition -.-> lab-13111{{"`Execute Function for Each List Element | Challenge`"}} python/build_in_functions -.-> lab-13111{{"`Execute Function for Each List Element | Challenge`"}} end

Execute Function for Each List Element

Problem

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.

Example

def print_square(num):
    print(num*num)

for_each([1, 2, 3], print_square) ## prints 1 4 9

In the example above, the for_each function is called with a list [1, 2, 3] and a function print_square. The print_square function is executed once for each element in the list, printing the square of each number.

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