Python Program for Linear Search
In Python, a linear search is a method of finding a specific element in a list or array by iterating through the collection one element at a time, until the target element is found.
This is an overall data structure in programming. It doesn’t matter which programming language you’re using or how you’re learning programming or DSA, you just need to know linear search.
Here is an example of a Python function that performs a linear search on a list:
def linear_search(lst, target): for i in range(len(lst)): if lst[i] == target: return i return -1 # Example usage numbers = [1, 5, 9, 2, 7] result = linear_search(numbers, 9) if result == -1: print("Element not found.") else: print("Element found at index", result)
This function takes a list lst
and a target element as input and returns the index of the first occurrence of the target element in the list. If the target element is not found in the list, the function returns -1.
Read More: Python Program to find the factorial of a number
It is worth noting that linear search is a simple and straightforward algorithm, but it can be relatively slow for large lists because it has to check every element in the list.
In python, the in
keyword is also used to check if an element is present in a list or not.
if target in lst: print(f"{target} is present in the list") else: print(f"{target} is not present in the list")