Articles

Program to implement linear search in python using for loop

Program to implement linear search in python using for loop


In the python programming article, we are going to learn

  • program to implement linear search in python using for loop

Linear Search in Python using for loop

The program to implement linear search in python using for loop is as follows:

 

# Owner : TutorialsInhand Author : Devjeet Roy

def linear_search(arr,element):
    for i in arr:
        if i == element:
            return arr.index(i)
        else:
            pass
    return -1

if __name__ == "__main__":
    numbers = list(map(int, input("Enter the numbers: ").strip().split()))
    val = int(input("Enter the value to be searched: ").strip())
    idx = linear_search(numbers,val)
    if idx == -1:
        print("Element not present in the list")
    else:
        print("Element is present at {} index position.".format(idx))

The output of the linear search in python code is as follows:

 

PS C:\Users\DEVJEET\Desktop\tutorialsInHand> python code.py
Enter the numbers: 1 2 3 4 5 6 7 8 9
Enter the value to be searched: 4
Element is present at 3 index position.
PS C:\Users\DEVJEET\Desktop\tutorialsInHand> python code.py
Enter the numbers: 1 2 3 4 5 6 7 8 9
Enter the value to be searched: 22
Element not present in the list

Few important tips about the program

1. In case of linear search, we iterate upon each and every element of the list. If the searable item matches with any element, we return the index of the element. Else we move on till the end of the list.

2. If the element is not present in the list, we can handle the situatation by returning -1 or anything the developer likes. (But not 0 as 0 is also an index position)

3. The time complexity is O(n)

 

linear search in python code snapshot:

linear search in python

This wraps up our session on linear search in python using for loop.


Python Programs

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Devjeet Roy
Full Stack Web Developer & Blockchain Enthusiast
Page Views :    Published Date : Aug 28,2022  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!