Stop when you find it
Return the first position of a value, or −1. About 7 minutes.
Stop as soon as you find it
You're looking for your friend's name on a class list. The moment you spot it, you stop reading. There's no point going through the rest of the list.
A loop can do the same: the moment a box holds what you want, return its box number straight away. Returning ends the function, so the rest of the loop never runs. That also means you always get the first match.
5 isn't 9. Keep going.
Saying "it isn't here"
If the loop gets to the end without returning, nothing matched. You still have to return something, and it mustn't look like a real box number. So return −1: no box is ever numbered −1, so nobody can mistake it for an answer.
Returning 0 would be a bug. Box 0 is a real box, the very first one.
for i in range(len(nums)):
if nums[i] == target:
return i
return -1A loop returns the box number as soon as it finds a 4. The array is 4, 7, 4, 1. What does it return?
- A0
- B2
- C−1
Show the answer
0. Box 0 already holds a 4, so it returns 0 and stops.
Find the first position
You get a list and a target. Return the index of the first box that holds the target. If the target isn't in the list, return -1.
nums = [5, 3, 9, 3, 8], target = 3 → 1
0 ≤ n ≤ 1,000