Skip to main contentSkip to solution

Arrange the following Python code (for searching a list) in correct sequence?

(A) if list[index] == key:

(B) for index in range(0, len(list)):

(C) def linearSearch(list, key):

(D) return index+1

Solution

✅ Correct Option: 2

The function must be defined first, then the loop, then the comparison inside the loop, then the return inside the if.

(C) def linearSearch(list, key): defines the function and its parameters.

(B) for index in range(0, len(list)): visits every position in the list.

(A) if list[index] == key: compares the current element with the key.

(D) return index+1 runs only when the element matches, and gives its position counting from 1.


Options 1 and 3: the if comes before the for loop, so index is not yet defined when it is used.

Option 4: return before the if would return on the first element without comparing it to the key.

Keyboard Shortcuts

  • Left arrow: Previous question
  • Right arrow: Next question
  • S key: Jump to solution
  • Q key: Jump to question