Python | Linear search on list or tuples
Last Updated :
13 Mar, 2023
Let us see a basic linear search operation on Python lists and tuples. A simple approach is to do a linear search, that is
- Start from the leftmost element of the list and one by one compare x with each element of the list.
- If x matches with an element, return True.
- If x doesn’t match with any of the elements, return False.
Example #1: Linear Search on Lists
Python
def search( List , n):
for i in range ( len ( List )):
if List [i] = = n:
return True
return False
List = [ 1 , 2 , 'sachin' , 4 , 'Geeks' , 6 ]
n = 'Geeks'
if search( List , n):
print ( "Found" )
else :
print ( "Not Found" )
|
Note: that lists are mutable but tuples are not.
Example #2: Linear Search in Tuple
Python
def search( Tuple , n):
for i in range ( len ( Tuple )):
if Tuple [i] = = n:
return True
return False
Tuple = ( 1 , 2 , 'sachin' , 4 , 'Geeks' , 6 )
n = 'Geeks'
if search( Tuple , n):
print ( "Found" )
else :
print ( "Not Found" )
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...