Python | Linear search in a list or tuple

Python Methods and Functions

A simple approach is a linear search , i.e.

  • Start at the leftmost element in the list and compare in x order with each element in the list.
  • If x matches an element, return True.
  • If x does not match any of the elements, return False.

Example # 1: Linear search through lists

# Function to search by parameter list name
# and value to search

def search ( list , n):

 

for i in range ( len ( list )):

if list [i] = = n:

  return True

  return False

 
# a list that 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" )

Exit :

 Found 

Note that the list is mutable and the tuples — no.

Example # 2: linear search in a tuple

# Search function by parameter list name
# and value to search

def search ( Tuple , n):

  

  for i in range ( len ( Tuple )):

if Tuple [i] = = n:

return True

return False

  
# a list that contains both string and numbers.

Tuple = ( 1 , 2 , 'sachin' , 4 , ' Geeks' , 6 )

 

 
Driver code

n = ' Geeks'

 

if search ( Tuple , n):

print ( "Found" )

else :

print ( " Not Found " )

Exit :

 Found 




Get Solution for free from DataCamp guru