How to make a Linear Search algorithm in Python

Опубликовано: 04 Август 2026
на канале: Terrible Tanker
34
3

This is an easy step-by-step explanation of a Linear search algorithm made especially for beginners to the world of programming and Python as a whole.
---------------------------------------------------------------------------------------------------------------------------
CODE:
def linear_search(array, value):#creats a function
#Loops through every value in list
for i in range(len(array)):
#checks if value is equal to target
if array[i] == value:
return i #Returns index which the value was found
return -1 # Returns -1
#Asks user to input a list of numbers
input_list = input("Enter a list of numbers separated by spaces or commas: ")

input_list = input_list.replace(',', ' ').strip()#Cleans up list so itcan handel both commas and spaces

array = [float(i) for i in input_list.split()]#turns input list into a list of floating numbers

value = float(input("Enter the number you want to search for: "))# Asks user for a value

result = linear_search(array, value) # Carries out linear search

if result != -1:#Outputs result
print(f"Element {value} found at index {result}")
else:
print(f"Element {value} not found")
---------------------------------------------------------------------------------------------------------------------------