Linear Search in Python

The linear search is the simplest approach to search for an element in a data set. This search algorithm iterates over all elements – from the beginning to the end – of a list until the element searched for is found. The result in the following example is the index of the value found. This search has an O(n) value according to the Big O notation.

my_list = [4, 12, 17, 33, 11, 53]

def linear_search(l, n):
    for i in range(0, len(l)):
        if l[i] == n:
            print("Element " + str(element) + " found at index " + str(i))

linear_search(my_list, 17)

In this example, the value “17” is searched for in the list. The result is the following output

Element 17 found at index 2

However, if the value you are looking for is not available, there will be no response.

A search is even easier with the in operator, which is implemented as a linear search:

my_list = [4, 12, 17, 23, 1, 66, 103]

def linear_search(element):
    if element in my_list:
        print("The element is in the list.")
    else:
        print("The element is not in the list.")

linear_search(17)

However, this example only tells you whether the element is in the list; the index is not determined.