Summery: In this article you can learn about the Linear Search in Python….

In this tutorial let’s see how to write a program to search a particular element from a list. So there are certain functions in python which helps you to do this very easily. But what if you want to do this manually. So let’s say that we have a list with the following values.

1 9 6 7 8 5 3 4 2

Now if you want to search the number “8” from this list obviously we have to run a loop. So this is how this loop going to work. First we take the first element from the list and compare it with the number that we want to search. In this case it’s number “8”. We have to continuously check the list items until we get a match to the number that we are looking.

Before implementing this idea in the code, you need to know few things about lists.

What is a List in Python?

It is a container used in data structures to store multiple data. These lists are ordered and they have index values for each items in the list. Python lists are written in between square brackets.

Elements inside these lists are indexed according to a sequence where index number 0 being the first element in the list. So for example let’s say we have a the below list.

list = [1,2,3,4,5]

In here the first item in the list is “1” and its index value is “0”. Second item in the list is “2”. It’s index value is “1” and so on…. So to access an item inside a list we need to call that specific item with its index value. For example, in the above list if we need to print the Second item in the list we need to say,

print(list[1])
Python Lists

So now, let’s start writing our code…

First let’s build a function to search this number. This function will take two parameters. They are, the list that we need to iterate through and the number that we need to search in that list. And inside the function lets iterate through the list using a while loop.

def search(list, n):
    i = 0
    while i < len(list):
          if list[i] == n:
            return True
          i = i + 1
    return False

list = [1,2,3,4,5]
n = 4

if search(list, n):
    print("Found")
else:
    print("Not Found")

So the above code will go through the entire list and check the number that we pass as “n” in the list. Inside this list I used the len function. This function will return the length of list.

Linear Search in Python

In the next tutorial lets learn about the binary search using python. Have a great day. Thank you.

Also Read: Python Tutorial for Beginners (Part 01)

Python Tutorial for Beginners (Part 02)

Python Tutorial for Beginners (Part 03)


0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *