Find the Last Matching Index (Challenge)

PythonPythonBeginner
Practice Now

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

Introduction

In Python, we can use a list comprehension and enumerate() to find the index of the last element in a list that satisfies a given condition. This challenge will test your ability to use these tools to solve a problem.


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(("`Python`")) -.-> python/AdvancedTopicsGroup(["`Advanced Topics`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") 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/lambda_functions("`Lambda Functions`") python/AdvancedTopicsGroup -.-> python/iterators("`Iterators`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13105{{"`Find the Last Matching Index (Challenge)`"}} python/conditional_statements -.-> lab-13105{{"`Find the Last Matching Index (Challenge)`"}} python/for_loops -.-> lab-13105{{"`Find the Last Matching Index (Challenge)`"}} python/lists -.-> lab-13105{{"`Find the Last Matching Index (Challenge)`"}} python/tuples -.-> lab-13105{{"`Find the Last Matching Index (Challenge)`"}} python/function_definition -.-> lab-13105{{"`Find the Last Matching Index (Challenge)`"}} python/lambda_functions -.-> lab-13105{{"`Find the Last Matching Index (Challenge)`"}} python/iterators -.-> lab-13105{{"`Find the Last Matching Index (Challenge)`"}} python/build_in_functions -.-> lab-13105{{"`Find the Last Matching Index (Challenge)`"}} end

Find the Last Matching Index

Problem

Write a function find_last_index(lst, fn) that takes a list lst and a function fn as arguments. The function should return the index of the last element in lst for which fn returns True. If no element satisfies the condition, the function should return -1.

Example

find_last_index([1, 2, 3, 4], lambda n: n % 2 == 1) ## 2
find_last_index([2, 4, 6, 8], lambda n: n % 2 == 1) ## -1

Summary

In this challenge, you learned how to use a list comprehension and enumerate() to find the index of the last element in a list that satisfies a given condition. This is a useful technique to have in your Python toolbox!

Other Python Tutorials you may like