Looking for one item
Search a list, return where you found it, and say so clearly when it isn't there. About 9 minutes.
Search, then stop
You look through your bag for your keys. The moment you find them, you stop looking. Searching a list works the same way.
This time you want the position, not the value, so loop over the positions. Look at the item in each box. As soon as one passes your test, return its position straight away. You already know the answer, so there's no need to look at the rest.
for i in range(len(nums)):
if nums[i] < 0:
return i- i
- 0
- x
- 5
Position 0 holds 5. It's not negative, so keep looking.
When it isn't there
What should the function return if nothing in the list passes the test? You can't return a position, because there isn't one. Programmers have a habit for this: return -1.
That works because no real position is ever negative, so -1 can't be confused with an answer. Put the return -1 after the loop. If the loop finishes without returning, nothing was found. Whoever calls your function knows what -1 means.
for i in range(len(nums)):
if nums[i] < 0:
return i
return -1A list has no negative numbers at all. What does the search function return?
- A-1
- B0
- CThe length of the list
Show the answer
-1. The loop finishes without finding anything, so the line after it returns -1.
First negative
Return the position of the first negative number in the list. Positions start at 0. If there is no negative number, return -1.
nums = [5, 3, 8, -2, 7] → 3
0 ≤ length of nums ≤ 100,000 · −1,000,000 ≤ nums[i] ≤ 1,000,000