# Linear search on list or tuples in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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.

## 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:

# 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
Tuple: 7 not found