Create a Python script to implement a linear search for a given list of numbers.…
- User
Create a Python script to implement a linear search for a given list of numbers. numbers_list = [1, 4, 5, 6, 7, 8 , 10] number = 6
Assistant
Here is the Python script to implement a linear search.
Python Code
def linear_search(lst, target): """ Performs a linear search for a target value in a list. Args: lst (list): The list to search through. target: The value to search for. Returns: int: The index of the target if found, otherwise -1. """ # Iterate through the list from index 0 to the end for i in range(len(lst)): # Check if the current element equals the target if lst[i] == target: return i # Return the index where the element is found return -1 # Return -1 if the element is not found in the list # Input data numbers_list = [1, 4, 5, 6, 7, 8, 10] number = 6 # Perform the search result_index = linear_search(numbers_list, number) # Output the results if result_index != -1: print(f"Number {number} found at index: {result_index}") else: print(f"Number {number} not found in the list.")