×

Python Program for Linear Search

Introduction

We employ specific algorithms to efficiently carry out our responsibilities, such as searching for an element in a given data structure. These algorithms fall under the category of searching algorithms. Searching algorithms include the following: the interpolation search algorithm, the linear search algorithm, the jump search algorithm, the binary search algorithm, etc.

The earliest and most basic searching algorithm out of all of these is the linear search method. This post will teach us how to build the Linear Search Method on a data structure and will also look at the Python3 implementation of the algorithm.

What is the Linear Search?

  • Finding items within a list can be done using a linear search strategy. Another name for it is a sequential search. Because it sequentially finds the required element, it is the easiest searching algorithm.
  • Every element is compared to the value that we are looking for. The element is found as well as the algorithm returns its key’s index position if both match.
  • The elements of a linear search don't have to be put in sorted order.
  • It is founded on a sequential technique.
  • Any linear data structure, including a linked list, array, etc., can be used to implement the linear search.
  • Both a single-dimensional array and a multidimensional array can use it.
  • The worst-case scenario for locating the element in the linear search is O (n).
  • The best-case scenario for discovering the first entry in a list in a linear search is O (1).
  • In the event of huge data sets, it is less effective.

Procedure:

When learning DSA (data structures and algorithms) for the first time, beginners frequently start with the linear search method. Let's use an illustration to demonstrate how the linear search algorithm can be used.

Let's say we want to look for the value=30 in the following data, which is in a Python List.

Python Program for Linear Search
  • Step 1: We take into account the first value, which is 21 from the list, and compare it to our search value, which is 30. We go on to the following value in the list because it is not equal.
  • Step 2: Next, we take into account the second factor, 65, and contrast it with the value of 30. We proceed to the following element once more because it is not equal.
  • Step 3: Our list now includes seven items. When we compare the two components, we discover that 7 is not equivalent to 30. We now go on to the next component.
  • Step 4: Element 30 is now on our list. 30 is compared to value = 30. We have located the element we were looking for in the list since 30 is equivalent to 30. The element's index value = 3 can then be returned for use in subsequent calculations after we print a message indicating that the element has been located.

This is an iterative process, as you can see, so this iteration will keep going until the preferred value is found or it moves to the end of the list. When it reaches the end of the list but no such element is there, it can display the message informing the user that such an element is not present.

This is the linear search algorithm, which you must have found to be fairly easy.

The complexity of Time:

  1. O(n), where n is the total number of elements in a list, is the worst case. The loop must be run n times in the worst-case scenario where the element is at the end of the list.
  2. Optimal Case: O (1). In the ideal scenario, the element appears at the top of the list.
  3. Case-average O (n). O(n) time complexity is obtained by adding up the total amount of time spent on each entry in the list and calculating their average.

Implementation of Python 3

Let's now see how this technique can be implemented in Python.

Code:

def linear_search (list_1, value):
    for i in range (len (list_1)):
        if list_1[i]== value:
            return i
    return -1


list_1=[21, 65, 7, 30, 132, 77, 16, 54]
x= int (input (" Enter the value you want to search in the list\n"))




index = linear_search (list_1, x)


if index == -1:
    print ("Search Complete! The element do not present in the list!")
else:
     print ("Search Complete! The element found at index " + str(index))

Now that we have the input of 30, let's examine the result:

Enter the value you want to search in the list
30
Search Complete! The element found at index 3

Let's look at what happens if we enter a number that isn't on the list, like value = 980:

Enter the value you want to search in the list
980
Search Complete! The element does not present in the list!

Because there are no 980 elements in the list, that is in fact the right outcome.

Conclusion

In this post, we have examined what a linear search algorithm is as well as in-depth examples of how to use it to find a certain element in a list. Finally, we demonstrated how we might use Python 3 as a language to actually execute the Linear Search Algorithm and obtain the results we needed.

Some Most Popular Questions

1. What are the linear search's space and time complexity?

When the data isn't ordered, linear search is a good strategy, however, it can be time-consuming. The program's memory usage and how long the compiler needs to run the program determine the time and space complexity, respectively. The time and space complexity of the linear search is listed below.

2. What is Interpolation Search?

The optimized variant of binary search, interpolation search, find the key element on average in O(log(log n)) time. In binary search, the mid of the array is the first place we always look. But using this approach, the search could lead to various places based on where the key is. The search will begin at the end of the array, for example, if the key is close to the final element.


Related Topics

Python Hash Table

An Introduction to Hashing A technique which used to identify a particular object uniquely from a set of similar objects is known as Hashing. Some real-life examples of hashing implementations include: A...

9 minutes read.

Python program to find the area of a circle

Python program to find the area of a circle This article will discuss how to find the area of a circle in Python with a given radius. The area of a...

2 minutes read.

Google Python Class

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

JWT Decode Python

Python's PyJWT package makes it possible to encrypt and decrypt JSON Web Tokens (JWT). JWT is a public, recognized global benchmark for safely expressing demands between two parties (RFC 7519). JSON...

7 minutes read.

How to plot multiple linear regression in Python

This article lets us look into linear regression in Python and how we can plot multiple linear regressions in it. Linear regression One of the simplest and most widely used Machine Learning...

4 minutes read.

Python String rindex() method

Python String rindex() method The string. rindex() method in Python returns the highest index of the substring inside the string (if found). If the substring is not found, it raises an...

2 minutes read.

Conditional Expressions in Python

In Python conditional expression are sometimes referred to operator called as ternary operator. Not only Python supports ternary operator but many other programming languages supports it. Ternary operator are the...

2 minutes read.

BOTTLE Python Web Framework

The Bottle is a lightweight WSGI micro web framework for python. It acts like a thin wrapper around a web server where it is distributed as a single file module...

4 minutes read.

Introduction to Scratch programming

Scratch programming is generally designed for children who may create digital stories, games, and animations using the computer language Scratch, which has the largest kid-focused community in the world. Scratch...

3 minutes read.

Python MySQL Delete Operation

Python MySQL Delete Operation: Like the update operation where we were updating required field from a SQL table, we can also delete an entry from the table which we have...

4 minutes read.

List Comprehension in Python3

List A list in python is a complex data type, and a list is a collection of the number of data. The data variable may or may not be of the...

5 minutes read.

Python Logistic Regression with Sklearn & Scikit

In this article, we'll walk through a tutorial for utilising the Python Sklearn (formerly known as Scikit Learn) package to implement logistic regression. To assist you in remembering the concept,...

18 minutes read.

How to make a firewall in Python?

Firewall: The firewall is a network which controls the incoming and outgoing network traffics of a monitor. It blocks the dataset based on the set of rules written in the security...

3 minutes read.

Scraping data in python

Data scraping is a technique in which one program extracts a set of data from the output of another program. Web scraping is the most common application of this technique....

6 minutes read.

_name_ in Python

Introduction: The code at level 0 indentation is to be performed when the command to run a Python program is supplied to the interpreter because Python does not have a main() function...

4 minutes read.

Index Error in Python

The index errors are the run time error that is raised in Python when we try to access an index that does not exist. This might seem very trivial but...

4 minutes read.

First Unique Character in a String Python

This article aims to introduce you to strings and how to create a string in Python, and then we will solve a simple yet exciting DSA (Data Structures and Algorithms)...

3 minutes read.

How to set font for Text in Python

As a tuple with the font family as the first component, a size in point as the second, and possibly a string with one or more of the style modifiers...

5 minutes read.

Python globals() function

Python globals() function The globals() function in Python returns the value of the named attribute of object where the ‘name’ must be a string. Syntax globals() Parameter NA Return This function returns the global symbol table as a dictionary. Example...

1 minute read.

Pltpcolor in Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.