Javatpoint Logo
Javatpoint Logo

Linear Search in Python

Python is one of the most popular and powerful languages. It takes a few lines to execute the code, which makes it much user-friendly language. In this tutorial, we will learn the linear search in Python. Searching is a technique to find the particular element is present or not in the given list.

There are two types of searching -

  • Linear Search
  • Binary Search

Both techniques are widely used to search an element in the given list.

What is a Linear Search?

Linear search is a method of finding elements within a list. It is also called a sequential search.  It is the simplest searching algorithm because it searches the desired element in a sequential manner.

It compares each and every element with the value that we are searching for. If both are matched, the element is found, and the algorithm returns the key's index position.

Concept of Linear Search

Let's understand the following steps to find the element key = 7 in the given list.

Step - 1: Start the search from the first element and Check key = 7 with each element of list x.

Linear Search in Python

Step - 2: If element is found, return the index position of the key.

Linear Search in Python

Step - 3: If element is not found, return element is not present.

Linear Search in Python

Linear Search Algorithm

There is list of n elements and key value to be searched.

Below is the linear search algorithm.

Python Program

Let's understand the following Python implementation of the linear search algorithm.



Element found at index:  4


In the above code, we have created a function linear_Search(), which takes three arguments - list1, length of the list, and number to search. We defined for loop and iterate each element and compare to the key value. If element is found, return the index else return -1 which means element is not present in the list.

Linear Search Complexity

Time complexity of linear search algorithm -

  • Base Case - O(1)
  • Average Case - O(n)
  • Worst Case -O(n)

Linear search algorithm is suitable for smaller list (<100) because it check every element to get the desired number. Suppose there are 10,000 element list and desired element is available at the last position, this will consume much time by comparing with each element of the list.

To get the fast result, we can use the binary search algorithm.

We have discussed the basic concept of the linear search. In the next tutorial, we will learn the second and most popular searching algorithm named Binary search.

Next TopicPython vs Scala

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA