Here’s an example of a linear search implementation in Python:
def linear_search(list, target_element):
for i, element in enumerate(list):
if element == target_element:
return i # Element found, return its index
return -1 # Element not found
if __name__ == '__main__':
list = [2, 3, 4, 10, 40]
target_element = 10
result = linear_search(list, target_element)
if result != -1:
print(f'Element {target_element} found at index {result}.')
else:
print(f'Element {target_element} not found in the list.')
You can learn and visualize the step-by-step execution of this code interactively on Coding Canvas, a platform designed to help students understand algorithms and programming visually!
https://codingcanvas.io/
https://codingcanvas.io/topics/
https://codingcanvas.io/topics/python/
https://codingcanvas.io/topics/python/linear-search