Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Computer Science Introduction to Algorithms Algorithms in Code Linear Search in Code

is it okay to do this? this code also gives the same result as the code taught in the video. What's the difference?

def linear_search(list,target):
  for item in list:
    if item == target:
      return list.index(item)
  return None


def verify(index):
  if index is not None:
    print("Target found at index: ",index)
  else:
    print("Target not found in the list")

numbers = [1,2,3,4,5,6,7,8,9,10]
result = linear_search(numbers, 6)
verify(result)

1 Answer

Dane Parchment
MOD
Dane Parchment
Treehouse Moderator 10,727 Points

Yes you are fine, at the end of the day a linear search is simply going through each element of the list until you find the first match.

How you traverse through the list is up to you, so long as you can:

  1. Traverse through each element in the list
  2. Exit the loop upon finding the first match.

You've done both here, so you're good. you understand the algorithm and can apply it.