Reverse Iteration in Python

PythonPythonBeginner
Practice Now

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

Introduction

In Python, we can use a for loop to iterate over a list and execute a function for each element. However, what if we want to start from the last element and work our way backwards? In this challenge, you will need to create a function that executes the provided function once for each list element, starting from the list's last element.


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-13642{{"Reverse Iteration in Python"}} python/for_loops -.-> lab-13642{{"Reverse Iteration in Python"}} python/lists -.-> lab-13642{{"Reverse Iteration in Python"}} python/tuples -.-> lab-13642{{"Reverse Iteration in Python"}} python/function_definition -.-> lab-13642{{"Reverse Iteration in Python"}} end

Execute function for each list element in reverse

Write a function for_each_right(itr, fn) that takes a list itr and a function fn as arguments. The function should execute fn once for each element in itr, starting from the last one.

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

Summary

In this challenge, you learned how to create a function that executes a provided function for each element in a list, starting from the last one. This can be useful when you need to process a list in reverse order.