← Python lessons

Tracking the Best Candidate

A loop can remember the best candidate examined so far. Decide what “best” means, choose an initial state, and replace the candidate only when a better one appears.

Distance from a target

abs(number) returns its absolute value: its distance from zero. The distance between two numbers is abs(first - second).

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

The results are 2, 2 and 0. Numbers on opposite sides of a target can be equally close. To keep the earlier candidate on a tie, update only when the new distance is strictly smaller.

No candidate yet

If a collection can be empty, its first item may not exist. Use None to represent “no candidate selected”. Test this with is None.

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

This prints Maya. The first item becomes the candidate without a comparison. Maya replaces Bo because it is longer. Alex has the same length, so Maya stays. An empty list leaves longest as None.

The candidate and its comparison value are different: longest stores the name, while len(longest) supplies the length used to compare it.

Optional shorter condition

The two branches above can be combined as if longest is None or len(name) > len(longest):, followed by longest = name.

Python evaluates or from left to right and skips its right side when the left side is true. This is why the condition does not try len(None). With and, Python skips the right side when the left side is false. You may keep the two-branch version while learning the pattern.

Check your understanding

Trace the longest-name example with an empty list and with ["Zoe", "Amy"]. Explain why changing > to >= would change the result for the second list.

Then calculate the distances of 6 and 14 from a target of 10. Which candidate should stay if 6 was processed first and ties keep the earlier candidate?


Practise this in the free Python course, where every exercise checks your code instantly.