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.
Python code
22 linesdef 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
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
- Use `next((i for i, x in enumerate(items) if condition(x)), -1)` for a one-liner
- 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
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.