Linear Search in Python

  1. Linear Search Algorithm
  2. Linear Search Python Implementation

If you want to understand Linear Search in detail then refer to the Linear Search Algorithm article.

Linear Search Algorithm

Let us assume that we have an unsorted array A[] containing n elements, and we want to find an element - X.

  • Traverse all elements inside the array starting from the leftmost element using a for loop and do the following:
    • If the value of A[i] matches with X, then return the index i. (If there can be multiple elements matching X, then instead of returning the index i, either print all indexes or store all the indexes in an array and return that array.)
    • Else move on to the next element.
    • If it is at the last element of the array, quit the for loop.
  • If none of the elements matched, then return -1.

Linear Search Python Implementation

def linearsearch(arr, n, x):
    for i in range(0, n):
        if (arr[i] == x):
            return i
    return -1

arr = [1, 2, 3, 4, 5]
x = 1
n = len(arr)
position = linearsearch(arr, n, x)
if(position == -1):
    print("Element not found !!!")
    print("Element is present at index", position)


Element is found at index: 1

The time complexity of the above algorithm is O(n).

DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python Algorithm

  • Python Bisect - Binary Search
  • Python Binary Search