Python | Linear search on list or tuples


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.

  1. LinearSearch(list, key)  
  2.   for each item in the list  
  3.     if item == value  
  4.       return its index position  
  5.    return -1  

Python Program

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

Program

Search function with parameter list name and the value to be searched

def search(list,n):

for i in range(len(list)): 
    if list[i] == n: 
        return True
return False

list which contains both string and numbers.

list = [1, 2, ‘sachin’, 4,’Geeks’, 6]

Driver Code

n = ‘Geeks’

if search(list, n):
print(“Found”)
else:
print(“Not Found”)


Like it? Share with your friends!

What's Your Reaction?

hate hate
0
hate
confused confused
0
confused
fail fail
0
fail
fun fun
0
fun
geeky geeky
0
geeky
love love
0
love
lol lol
0
lol
omg omg
0
omg
win win
0
win
Choose A Format
Personality quiz
Series of questions that intends to reveal something about the personality
Trivia quiz
Series of questions with right and wrong answers that intends to check knowledge
Poll
Voting to make decisions or determine opinions
Story
Formatted Text with Embeds and Visuals
List
The Classic Internet Listicles
Countdown
The Classic Internet Countdowns
Open List
Submit your own item and vote up for the best submission
Ranked List
Upvote or downvote to decide the best list item
Meme
Upload your own images to make custom memes
Video
Youtube and Vimeo Embeds
Audio
Soundcloud or Mixcloud Embeds
Image
Photo or GIF
Gif
GIF format