← Python lessons

Tracking the Best Candidate

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

To find the best candidate in a list, a loop keeps the best item seen so far and replaces it only when a better one appears.

Keep the best so far

Start with the first item as the best. Then compare each item with it.

names = ["Bo", "Maya", "Alex"]longest = names[0]for name in names:    if len(name) > len(longest):        longest = nameprint(longest)

This prints Maya. Maya replaces Bo because it is longer. Alex has the same length, so Maya stays.

longest stores the name. len(longest) is the value you compare. Using > keeps the earlier name on a tie. With >=, Alex would replace Maya.

Closest to a target

Sometimes "best" means closest to a target. abs(number) gives a number's distance from zero, so abs(first - second) is the distance between two numbers.

print(abs(8 - 10))print(abs(12 - 10))print(abs(10 - 10))

This prints 2, 2 and 0. 8 and 12 are equally close to 10. Smaller distance is better, so compare with <.

No candidate yet

An empty list has no first item. Start with None, which means "no candidate yet". Test it with is None.

longest = Nonefor name in ["Bo", "Maya", "Alex"]:    if longest is None:        longest = name    elif len(name) > len(longest):        longest = nameprint(longest)

This prints Maya. The first name becomes the candidate without a comparison. With an empty list, the loop never runs and longest stays None.

Check your understanding

Trace the last example with an empty list and with ["Zoe", "Amy"]. Why would >= change the result for the second list?

What are the distances of 6 and 14 from a target of 10? If 6 comes first and ties keep the earlier item, which one stays?

See also: The Accumulator Pattern.

Your turn

Keep the shortest name in best. Replace it only for a strictly shorter name, so ties keep the earlier name.

🎯 Goal — make it print exactly:
Bo
names = ["Maya", "Bo", "Alex", "Jo"]best = names[0]for name in names:    # add two lines: compare lengths with if, then update best    passprint(best)

Advanced reading

Practise this lesson

This exercise uses this lesson. It runs in your browser and checks your code instantly — no sign-up needed.

Python Fundamentals