Linear search on list or tuples in Python

PythonServer Side ProgrammingProgramming

In this article, we are going to learn how to apply a linear search on lists and tuples.

A linear search starts searching from the first element and goes till the end of the list or tuple. It stops checking whenever it finds the required element.

Linear Search - Lists & Tuples

Follow the below steps to implement linear search on lists and tuples.

  • Initialize the list or tuple and an element.
  • Iterate over the list or tuple and check for the element.
  • Break the loop whenever you find the element and mark a flag.
  • Print element not found message based on the flag.

Example

Let's see the code.

# function for linear search
def linear_search(iterable, element):
   # flag for marking
   is_found = False
   # iterating over the iterable
   for i in range(len(iterable)):
      # checking the element
      if iterable[i] == element:
         # marking the flag and returning respective message
         is_found = True
         return f"{element} found"

   # checking the existence of element
   if not is_found:
      # returning not found message
      return f"{element} not found"

# initializing the list
numbers_list = [1, 2, 3, 4, 5, 6]
numbers_tuple = (1, 2, 3, 4, 5, 6)
print("List:", linear_search(numbers_list, 3))
print("List:", linear_search(numbers_list, 7))
print("Tuple:", linear_search(numbers_tuple, 3))
print("Tuple:", linear_search(numbers_tuple, 7))

If you run the above code, then you will get the following result.

Output

List: 3 found
List: 7 not found
Tuple: 3 found
Tuple: 7 not found

Conclusion

If you have any queries in the article, mention them in the comment section.

raja
Published on 13-Nov-2020 18:21:40
Advertisements