Find the Last Index Where a Condition Is True in Python
This code scans a sequence from the end and returns the index of the last element that satisfies a given condition, or -1 if none do.
Python code
20 linesdef last_index_where(sequence, condition):
"""Return the index of the last element in sequence that satisfies condition."""
for i in range(len(sequence) - 1, -1, -1):
if condition(sequence[i]):
return i
return -1
if __name__ == "__main__":
numbers = [1, 4, 7, 2, 9, 5, 8, 3]
is_even = lambda x: x % 2 == 0
result = last_index_where(numbers, is_even)
print(f"Last even number index: {result}")
is_greater_than_six = lambda x: x > 6
result2 = last_index_where(numbers, is_greater_than_six)
print(f"Last number > 6 index: {result2}")
is_negative = lambda x: x < 0
result3 = last_index_where(numbers, is_negative)
print(f"Last negative number index: {result3}")
Output
Last even number index: 6
Last number > 6 index: 7
Last negative number index: -1
How it works
The function iterates backwards using range(len(sequence) - 1, -1, -1), which starts at the last index and moves down to 0. For each index, it calls the condition callable on the element. The first match found during this reverse scan is the last occurrence, so it returns immediately, making the search efficient with a worst-case time complexity of O(n). If no element matches, the loop completes and the function returns -1, a common convention for "not found".
Common mistakes
- Using `for i in range(len(sequence))` and breaking at the first match, which returns the first index instead of the last.
- Forgetting to go down to -1 to include index 0 in the range.
- Passing a condition that raises an exception for some elements (e.g., `x % 2` on non-numeric types).
- Not returning -1 explicitly when no match is found.
Variations
- Use a reversed loop with `for i, val in reversed(list(enumerate(sequence)))`: `for i, val in reversed(list(enumerate(sequence))): if condition(val): return i`.
- Use `next` with a generator: `return next((i for i in range(len(sequence)-1, -1, -1) if condition(sequence[i])), -1)`.
Real-world use cases
- Finding the most recent failed job in a processing queue by scanning timestamps in reverse.
- Locating the last stock price that crossed a threshold before a given date in financial data.
- Determining the index of the most recent user action matching a filter in an event log.
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.