Find All Matching Indexes

Beginner

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

Introduction

In Python, we can use the enumerate() function to iterate over a list and get both the index and the value of each element. We can also use list comprehension to filter elements that satisfy a certain condition. In this challenge, you will use these concepts to create a function that finds the indexes of all elements in a list that satisfy a given testing function.

Find All Matching Indexes

Write a function find_index_of_all(lst, fn) that takes a list lst and a testing function fn as arguments and returns a list of indexes of all elements in lst for which fn returns True.

Input

  • A list lst of integers.
  • A testing function fn that takes an integer as input and returns a boolean value.

Output

  • A list of integers representing the indexes of all elements in lst for which fn returns True.
def find_index_of_all(lst, fn):
  return [i for i, x in enumerate(lst) if fn(x)]
find_index_of_all([1, 2, 3, 4], lambda n: n % 2 == 1) ## [0, 2]

Summary

In this challenge, you learned how to use enumerate() and list comprehension to find the indexes of all elements in a list that satisfy a given testing function. You can now use this knowledge to solve similar problems in the future.