DEV Community

Cover image for Linear Search Algorithm Using Python
Abhishek Ezhava
Abhishek Ezhava

Posted on

1 1

Linear Search Algorithm Using Python

What is a Linear Search?

A linear search is the most basic kind of search that is performed. So how is it performed? A linear or sequential search, as the name suggests, is done when you inspect each item in a list one by one from one end to the other to find a match for what you are searching for. You often do this in your daily life, say when you are looking through your shopping list to cross out an item you have picked up.

Benefits and Drawbacks
The benefit is that it is a very simple search and easy to program. In the best-case scenario, the item you are searching for may be at the start of the list in which case you get it on the very first try.

Its drawback is that if your list is large, it may take a while to go through the list. In the worst-case scenario, the item you are searching for may not be in the list, or it may be at the opposite end of the list.

Coding a Linear Search
Let's first develop an algorithm for performing a linear search. We will then convert this into a Python script.

Let's start with a list of numbers, say 10 of them
First, we will ask for a number we think may be in the list. We will call this variable ''searchItem''
Also, we will set a flag variable called ''found'' to false
Now loop thru the entire list from start to end
Compare the item at the current position in the list with ''searchItem''
If it matches then set ''found'' to true and exit the loop, else move on to the next position
Otherwise, if we have searched the entire list, ''searchItem'' was not found, so ''found'' remains false

Alt Text

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more