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
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
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.
Related questions:
2026: 29 May Shift 1
2026: 26 May Shift 1
2025: 15 May Shift 2
2026: 11 May Shift 2
2025: 15 May Shift 2