Loop-Else: Search for a Target Value

Medium ⏱ 12 min 64% acceptance ★★★★★ 4.5
Write a function find_index_or_report(nums, target) that searches nums for target using a for...else construct: if found, return its index immediately (breaking the loop); if the loop completes without finding it, the else clause should return -1.

Examples

Example 1
Input
find_index_or_report([4, 8, 15, 16], 15)
Output
2
Explanation

15 is at index 2.

Example 2
Input
find_index_or_report([4, 8, 15, 16], 99)
Output
-1
Explanation

Loop completes without a break, so else runs.

Constraints

  • nums is a list of numbers.
  • Must use a for...else construct with break.

Topics

Loopsloop-elsefor loop

Companies

NetflixAtlassian

Hints

Hint 1

The `else` block on a for loop only executes if the loop was never `break`-ed out of.

Hint 2

Use `enumerate()` to get both index and value while iterating.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.