Table of Contents

Python Code for Linear Search in a List

Example Description
Learn to write a Python function to check if a number is present in a list using linear search. Get code and understand the logic behind it.

Introduction:

In this Python code example, we’ll learn how to implement a linear search algorithm to check if a number is present in a list. Linear search is a basic search algorithm that sequentially checks each element in a list until a match is found or all the elements have been exhausted. We’ll define a function called `linearSearch()` that takes a number and a list as input and returns the position of the number if it is present in the list, or None if it is not.

Code:

#Function to check if a number is present in the list or not
def linearSearch(num,list1):
 for i in range(0,len(list1)):
  if list1[i] == num: #num is present
    return i #return the position
 return None #num is not present in the list
#end of function
list1 = [] #Create an empty list
print("How many numbers do you want to enter in the list: ")
maximum = int(input())
print("Enter a list of numbers: ")
for i in range(0,maximum):
 n = int(input())
 list1.append(n) #append numbers to the list
num = int(input("Enter the number to be searched: "))
result = linearSearch(num,list1)
if result is None:
 print("Number",num,"is not present in the list")
else:
 print("Number",num,"is present at",result + 1, "position")

Logic:

  1. Define a function called `linearSearch()` that takes two parameters: `num` and `list1`.
  2. Iterate through the elements in the list using a `for` loop and the `range()` function.
  3. Check if the current element in the list is equal to the provided number (`num`).
  4. If a match is found, return the index (`i`) of the element in the list.
  5. If no match is found after iterating through all the elements, return None.
  6. Create an empty list called `list1`.
  7. Prompt the user for the maximum number of numbers they want to enter in the list.
  8. Use a `for` loop and the `input()` function to add the numbers to the list using the `append()` method.
  9. Prompt the user to enter the number they want to search for in the list.
  10. Call the `linearSearch()` function with the provided number and the list.
  11. Check if the result returned by the function is None.
  12. If it is, print a message stating that the number is not present in the list.
  13. If it is not None, print a message stating that the number is present at the position returned by the function.

Output:

>> How many numbers do you want to enter in the list:5

>> Enter a list of numbers:

1

2

3

4

5

Enter the number to be searched:4

Number 4 is present at 4 position