-
Hajipur, Bihar, 844101
Linear Search is the simplest searching algorithm. It goes through each element in a list or array one by one to find the target value.
Use Linear Search when:
The list is unsorted
Simplicity is preferred over performance
The list is small
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
numbers = [10, 20, 30, 40, 50]
target = 30
result = linear_search(numbers, target)
print("Found at index:", result)
✅ Output:
Found at index: 2
target = 99
result = linear_search(numbers, target)
if result == -1:
print("Element not found.")
else:
print("Found at index:", result)
✅ Output:
Element not found.
Case | Time |
---|---|
Best Case | O(1) |
Worst Case | O(n) |
Average | O(n) |
Linear Search is not efficient for large datasets.
Searching in an unsorted list
Finding the first match
Easy to implement without any libraries
Q1. Write a Python program to search for number 25
in a list of 10 elements using linear search.
Q2. Write a Python program to modify the search function to return True
or False
instead of the index.
Q3. Write a Python program to perform linear search in a list of strings.
Q4. Write a Python program to handle the case where the target occurs more than once and return all indices.
Q5. Write a Python program to modify the search function to print the number of comparisons made.
Q6. Write a Python program to accept a list and a target value from the user and search for that value.
Q7. Write a Python program to return the last occurrence of the target element in the list.
Q8. Write a Python program to search for a number in a nested list (list of lists).
Q9. Write a Python program to check if a value is present in a list of dictionaries by a specific key.
Q10. Write a Python program to implement linear search without using range()
or index values – iterate directly through elements.
Q1: What is Linear Search?
Q2: What is the best-case time complexity of linear search?
Q3: What does linear search return if element not found?
Q4: Which data type can you search using linear search?
Q5: Which one is true about linear search?
Q6: In which case is linear search fastest?
Q7: How many elements are checked in worst case (length n)?
Q8: What is returned on successful match?
Q9: Is linear search case-sensitive on strings?
Q10: What does arr[i] == target do?