## Python program for linear search

Searching in linear fashion is called as linear search. Membership operator “in” is used to iterate in sequence while linear search. Linear search can be performed on sorted or unsorted sequence.

Example: Consider a sequence on numbers as 6,5,4,8,8,9,3,21,4,7,2

If number to be searched is 3, then 3 will b compared linearly with the first element of sequence, in our case 3 will be compared with 6.

As it is not equal 3 will be compared with next value ie. 5 and will continue so on.

If 3 is present in sequence it will return the output otherwise will compare till last element of the sequence.

Advantage

If number is present in the sequence boolean value will be returned.

Disadvantage

If number is present at the end of the sequence then linear search will consume more time.

Following program will help university students and beginners to understand the concepts and working of Linear search.

""" Author : ITVoyagers (itvoyagers.in) Date :5th December 2019 Description : Python program for linear search """ collection = [125,126,127,128,129,141,145,146] print("list of items is", collection) itv = int(input("enter item to search:")) p = 0 temp = 0 while p < len(collection): if collection[p] == itv: temp = 1 break p = p + 1 if temp == 1: print("item found at position:", p) else: print("item not found")

**Output:**

>>> list of items is [125, 126, 127, 128, 129, 141, 145, 146] enter item to search:140 item not found >>> ================================ RESTART ================================ >>> list of items is [125, 126, 127, 128, 129, 141, 145, 146] enter item to search:141 item found at position: 5 >>>

**Note : Please note that above program is compatible with Python 3 or higher version.**

Please check out other practical related to Data structures

## 1 thought on “Python program for linear search”