w3resource

Python: Find the index of the first element in the given list that satisfies the provided testing function


First Index Satisfying Function

Write a Python program to find the index of the first element in the given list that satisfies the provided testing function.

Use a list comprehension, enumerate() and next() to return the index of the first element in nums for which fn returns True.

Sample Solution:

Python Code:

# Define a function 'find_index' that takes a list 'nums' and a function 'fn' as input.
def find_index(nums, fn):
    # Use a generator expression to find the first index 'i' where 'fn(x)' is True for an element 'x' in 'nums'.
    return next(i for i, x in enumerate(nums) if fn(x))

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

Sample Output:

0

Flowchart:

Flowchart: Find the index of the first element in the given list that satisfies the provided testing function.

For more Practice: Solve these Related Problems:

  • Write a Python program to find the index of the first element in a list that satisfies a complex condition defined by a lambda function.
  • Write a Python program to determine the first index where the square of an element is greater than a specified threshold.
  • Write a Python program to find the index of the first element that meets a provided function, returning -1 if no element qualifies.
  • Write a Python program to retrieve both the index and value of the first list element that passes a custom test function.

Go to:


Previous: Write a Python program to get every element that exists in any of the two given lists once, after applying the provided function to each element of both.
Next: Write a Python program to find the indexes of all elements in the given list that satisfy the provided testing function.

Python Code Editor:

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.