Table of Contents

Linear Search Algorithm in Python

Example Description
Learn how to perform linear search in Python to find an element in a list. Understand the logic, implementation, and output of the linear search algorithm.

Introduction:

This Python code demonstrates the implementation of the linear search algorithm. Linear search is a simple searching algorithm that sequentially checks each element in a list until a match is found or the entire list has been searched. It’s a straightforward method but might not be efficient for large datasets.

Code:

def linearSearch(list, key):
    # function to perform the search
    for index in range(0, len(list)):
        if list[index] == key:  # key is present
            return index + 1  # position of key in list
    return None  # key is not in list
# end of function

list1 = []  # Create an empty list
maximum = int(input("How many elements in your list? "))
print("Enter each element and press enter: ")
for i in range(0, maximum):
    n = int(input())
    list1.append(n)  # append elements to the list
print("The List contents are:", list1)
key = int(input("Enter the number to be searched:"))
position = linearSearch(list1, key)
if position is None:
    print("Number", key, "is not present in the list")
else:
    print("Number", key, "is present at position", position)

Logic:

  1. The linearSearch function takes a list and a key as its parameters.
  2. It iterates through each element in the list and compares it with the key.
  3. If a match is found, the function returns the position (index + 1) of the key in the list.
  4. If no match is found after checking all elements, the function returns None to indicate that the key is not present in the list.
  5. The user is prompted to enter the number of elements in the list and the elements themselves.
  6. The linearSearch function is called to search for the user-provided key in the list.
  7. The program outputs whether the key is present in the list and its position if found.

Output:

>>How many elements in your list? 5

>>Enter each element and press enter:

>>12

>>45

>>8

>>3

>>67

>>The List contents are: [12, 45, 8, 3, 67]

>>Enter the number to be searched: 8

>>Number 8 is present at position 3