w3resource

Python: Find the indexes of all elements in the given list that satisfy the provided testing function


All Indices Satisfying Function

Write a Python program to find the indexes of all elements in the given list that satisfy the provided testing function.

Use enumerate() and a list comprehension to return the indexes of the all element in lst for which fn returns True.

Sample Solution:

Python Code:

# Define a function 'find_index_of_all' that takes a list 'lst' and a function 'fn' as input.
def find_index_of_all(lst, fn):
    # Use a list comprehension to find and collect the indices 'i' where 'fn(x)' is True for an element 'x' in 'lst'.
    return [i for i, x in enumerate(lst) if fn(x)]

# Call the 'find_index_of_all' function with an example list and a lambda function that checks if a number is odd.
print(find_index_of_all([1, 2, 3, 4], lambda n: n % 2 == 1)) 

Sample Output:

[0, 2]

Flowchart:

Flowchart: Find the indexes of all elements in the given list that satisfy the provided testing function.

For more Practice: Solve these Related Problems:

  • Write a Python program to find all indices of elements in a list that satisfy a given predicate and return them in sorted order.
  • Write a Python program to retrieve the indices of all even numbers in a list using a provided testing function.
  • Write a Python program to find all indices of elements that are prime numbers in a list and count the total occurrences.
  • Write a Python program to extract and display the indices of all list elements that satisfy a custom lambda function.

Python Code Editor:

Previous: Write a Python program to find the index of the first element in the given list that satisfies the provided testing function.
Next: Write a Python program to split values into two groups, based on the result of the given filter list.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.