Linear Search in Python
Here you will get the program code of Linear Search in Python programming. To write a python program linear search we will be using for loop and user defined own function.
Linear Search is a type of search algorithm that sequentially checks each element in a list until it finds the desired item.
Program Code of Linear Search in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #Python Linear Search program def linear_search(items, n): for i in range(len(items)): if items[i] == n: return i return -1 items = [] print("Enter 5 numbers ") for i in range(5): item = input('Input item : ') items.append(item) n = input("Enter a number to search location : ") result = linear_search(items, n) if result == -1: print("Element is not present in array") else: print("Element is present at index", result) |
Output
Enter 5 numbers
Input item : 2
Input item : 1
Input item : 4
Input item : 3
Input item : 8
Enter a number to search location : 3
Element is present at index 3
Check out our other Python programming examples