Python Program for Linear Search

Python Program for Linear Search. Linear search, also known as sequential search, is one of the simplest search algorithms. It works by checking each element of a list or array sequentially until the desired element is found or the list ends this method is straightforward and does not require data to be sorted.

Linear search is particularly useful when dealing with small or unsorted datasets where the simplicity of implementation is more critical than the efficiency of the search. It is the ease of understanding makes it a perfect starting point for learning about search algorithms.

Let’s explore how to implement linear search in Python. we will create a function that takes two parameters: A list and the item to be searched. The function will return the index of the item if found; otherwise, it will return -1, Indicating the item is not in the list.

Define the Function


  • 'arr': The list or array in which to search.
  • 'x': The item to be searched
  • The 'for' loop iterates over each element in the list.
  • The 'if' statement checks if the correct element matches the item 'x'.
  • If a match is found, it returns the index 'i'.
  • If no match is found by the end of the loop, the function returns '-1'.

Test the Function

To ensure our function works as expected, let’s test the linear search function.

linear search in python

Linear Search Time Complexity

A time complexity of linear search is O(n), where n is the number of elements in the list. This is because, in the worst case, every element needs to be checked. This makes linear search inefficient for large datasets.

Linear search is an easy-to-understand and easy-to-implement algorithm suitable for small or unordered datasets. while not the fastest, its simplicity makes it an essential algorithm for beginners to learn and understand basic searching techniques in computer science.

Happy Coding & Learning

See Also

1 thought on “Python Program for Linear Search”

Leave a Comment