Linear Search in Python — Python Technical Interview Questions & Answers
Linear Search in Python
Linear Search in Python
- Linear search checks each item from start to end until it finds the target. Works on unsorted lists. Worst case you look at all n items — O(n). Code is a for-loop and an if. Acceptable on small lists or when data is not sorted. On a huge sorted list, binary search is the better story.
- Trace [4, 1, 3, 2] looking for 3: check 4, check 1, check 3 — found. Say O(n) honestly. Don’t claim it is “always slow” — for n=10 it is fine.
- Linear Search in Python — output: 1. 90 is at index 1. If missing, found stays -1.
Technical Interview Tip: When linear search is acceptable.
Code Examples for Linear Search in Python
Example
# Linear search
marks = [70, 90, 80]
key = 90
found = -1
for i, x in enumerate(marks):
if x == key:
found = i
break
print(found)
Linear Search in Python — output: 1. 90 is at index 1. If missing, found stays -1.
How to Explain Linear Search in Python to an Interviewer
Explain Linear Search as if you are teaching a junior — definition, then one tiny script.
Scan one by one. Works unsorted. O(n).
What does the example print, and why?
Linear Search in Python — output: 1
What mistake do freshers make with Linear Search?
Easy to code.