Python bootcamp · Lab 36

Linear search

mediumLinear Search12 minLesson: Linear Search

Read the question, write Python on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

The first line is n. The second line has n integers. The third line is a target.

Print the 0-based index of the first time the target appears, or -1 if it is missing.

Input. Line 1: n. Line 2: n integers. Line 3: target.

Output. One integer: the index, or -1.

Constraints

  • 1 ≤ n ≤ 1000

Examples

Example 1
Input
5
3 1 8 2 4
8
Output
2
Example 2 — Not in the list.
Input
4
1 2 3 4
9
Output
-1
Hint
  1. A for-loop with enumerate finds the first hit.
  2. list.index(target) raises if missing — catch it, or scan by hand.
Show correct code

Peek only after you have tried. You can still Check your own version.

n = int(input())
nums = list(map(int, input().split()))
target = int(input())
print(nums.index(target) if target in nums else -1)
main.pyPython · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.