linear search on tuple in python

In this example, you will try to find element from tuple using linear search.

What is Linear Search?

A linear search or sequential search is a method for finding an element within a data. The algorithm begins from the first element of the tuple, starts checking every element until the expected element is found.

Example :

# python program for linear search on tuple

#define tuple
tpl = (1,34,23,65,25,77,43,75,90)

x = int(input("Enter number to search in tuple : "))

flag = False
for i in range(len(tpl)):
        if tpl[i] == x:
            flag = True
if flag == 1:
    print('{} was found at index {}.'.format(x, i))
    print('{} was not found.'.format(x))

Output :

//Output - 1
Enter number to search in tuple : 75
75 was found at index 7.

Explanation :

In above code, first of all user will input value to search then program will loop entire tuple data and check entered element is exist in tuple. If element is in tuple then it will print message with it's index otherwise it will print "Not Found" message.

Share your thoughts

Ask anything about this examples