Python Program for Linear Search. Creating a Python program to perform a linear search is an excellent exercise for beginners to understand basic programming concepts like loops and conditional statements. A linear search is a straightforward searching algorithm that checks each element of a list sequentially until the desired element is found or the list ends. This tutorial will guide you through writing a Python program to implement a linear search.
Table of Contents
Linear Search
Linear search also known as sequential search, is the simple searching algorithm. Given a list(or array) and a value to find, the algorithm starts at the beginning of the list and checks every element until it finds the target value or reaches the end of the list.
Implementing Linear Search in Python
First, you need to define a function that performs the linear search. This function will take two parameters: The list in which to search and the value to find.
def linear_search(arr, target):
#
Iterate over the List
Inside the function, use a loop to iterate over the list. You will check each element to see if it matches the target value.
for i in range(len(arr)):
if arr[i]==target:
return i
In this snippet, 'i'
is the index of the current element. If the current element matches the target value, the function returns the index of that element.
Return a Result
If the loop is complete without finding the target, it means that the value is not in the list. After the loop, you can return a value that indicates the target was not found. ‘-1’ is a common choice because it can not be an index in a list.
return -1
Complete Linear Search Function
Here is how the complete function looks:
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i]==target:
return i
return -1
Complete Python Program for Linear Search
To use the linear search function, you need a list to search and a target value. Here is a complete Python program for linear search.
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i]==target:
return i
return -1
list = [10,21,32,8,5,3]
target = 32
result = linear_search(list,target)
if result != -1:
print("Target value found at index: ",result)
else:
print("Target value not found in the list")
Congratulations!! You have written a Python Program to perform a linear search. This tutorial introduced you to essential programming concepts such as defining functions, looping through lists, and using conditional statements.
Happy Coding & Learning
1 thought on “Python Program for Linear Search”