w3resource

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

Python List: Exercise - 230 with Solution

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.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/list/python-data-type-list-exercise-230.php