Find the Index of a Value

Easy ⏱ 8 min 82% acceptance ★★★★☆ 4.4
Write safe_index(items, target) that returns the index of the first occurrence of target in items, or -1 if target is not found. Do not let an exception propagate.

Examples

Example 1
Input
items = ['a', 'b', 'c'], target = 'b'
Output
1
Explanation

'b' is at index 1.

Example 2
Input
items = ['a', 'b'], target = 'z'
Output
-1
Explanation

'z' is not present.

Constraints

  • 0 <= len(items) <= 10^5

Topics

ListsSearching

Companies

TCSWipro

Hints

Hint 1

.index() raises ValueError when missing — check with `in` first, or wrap it in a try/except.

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