python program for linear search

In this example, you will try to find element from list using linear search.

What is Linear Search?

A linear search or sequential search is a method for finding an element within a list.The algorithm begins from the first element of the list, starts checking every element until the expected element is found.

Example :

    
# Python program to perform linear search on list
#define list
lst = [1,34,23,65,25,77,43,75,90]

#take input number to be find in list   
x = int(input("Enter number to search in list : "))

for i in range(len(lst)):
        if lst[i] == x:
            print('{} was found at index {}.'.format(x, i))
            
print('{} was not found.'.format(x))
       

Output :

    
//Output - 1
Enter number to search in list : 25
25 was found at index 4.

//Output - 2
Enter number to search in list : 99
99 was not found.
    

Explanation :

In above code, first of all user will input value to search then program will loop entire list and check entered element is in list or not. If element is in list then it will print message with it's index otherwise it will print "Not Found" message.


Share your thoughts

Ask anything about this examples