Find the First Index Where a Condition Is True in Python

Search any iterable for the first element matching a predicate and return its index, or -1 if none match.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 12 views 0 copies

Python code

22 lines
Python 3.9+
def first_true_index(items, condition):
    """Return the first index where condition(item) is True, or -1 if none match."""
    for i, item in enumerate(items):
        if condition(item):
            return i
    return -1


if __name__ == "__main__":
    numbers = [1, 3, 5, 8, 10, 12]
    # Find first number greater than 5
    index = first_true_index(numbers, lambda x: x > 5)
    print(f"First index where x > 5: {index}")
    
    strings = ["apple", "banana", "cherry", "date"]
    # Find first string starting with 'c'
    idx = first_true_index(strings, lambda s: s.startswith("c"))
    print(f"First index where string starts with 'c': {idx}")
    
    # Example where no item matches
    no_match = first_true_index(numbers, lambda x: x > 100)
    print(f"First index where x > 100 (no match): {no_match}")

Output

stdout
First index where x > 5: 3
First index where string starts with 'c': 2
First index where x > 100 (no match): -1

How it works

The enumerate function pairs each item with its index, so you can return the position as soon as condition returns True. The loop stops early once a match is found, making this O(n) in the worst case and often faster in practice. If no element satisfies the predicate, the function falls through to return -1, following the common convention used by methods like list.index().

Common mistakes

  • Confusing element value with its index when checking the condition
  • Forgetting to return -1 when no match exists, leading to implicit None
  • Assuming the condition runs on indexes instead of items

Variations

  1. Use `next((i for i, x in enumerate(items) if condition(x)), -1)` for a one-liner
  2. Return the item itself instead of the index with `next((x for x in items if condition(x)), None)`

Real-world use cases

  • Locating the first failed test in a suite to report which check broke the build.
  • Finding the first element in a log that exceeds a severity threshold during alerting.
  • Scanning a queue for the first message that matches a routing rule before processing it.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.