FAQ: Linear Search: Python - Finding Duplicates

This community-built FAQ covers the “Finding Duplicates” exercise from the lesson “Linear Search: Python”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Search Algorithms

FAQs on the exercise Finding Duplicates

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

What is this supposed to mean? Is this Venus, Ankh, female or copper? And why here?
ekhmakhn

1 Like

You typed it wrong, it’s meant to be an up arrow.

This algorithm works in theory, but unfortunately the result that is given by the algorithm only shows the first instance of New York city and not the second one. No error is raised, and the for loop stops when we don’t want it to.

# Search list and target value tour_locations = [ "New York City", "Los Angeles", "Bangkok", "Istanbul", "London", "New York City", "Toronto"] target_city = "New York City" #Linear Search Algorithm def linear_search(search_list, target_value): matches = [] for idx in range(len(search_list)): if search_list[idx] == target_value: matches.append(idx) if len(matches) != 0: return matches else: raise ValueError("{0} not in list".format(target_value)) #Function call tour_stops = linear_search(tour_locations, target_city) print(tour_stops)

We get [0] as a result, when really we should be getting [0,5] since New York City is in index 0 and 5 in the list.

Please help me understand what is going on, and how the algorithm can be modified to include the second instance.

You could remove the return and raising the error from the loop,
so that the loop continues to run after the first match,
and put return matches outside the loop (after the loop)
If you want to raise an error if there’s no matches,
you could have

  if len(matches) == 0:  # no matches (nothing in list)
    raise ValueError("{0} not in list".format(target_value))

outside the loop, but before the return