Start learning free

LESSON 185 OF 673 · LOOPING OVER LIST INDICES

Top K Brands V3 in Python: Finding the Maximum in a List

Practice Read the full explanation

Many brands sell the same product, stored in two parallel lists: ratings[i] is the rating of brands[i]. Find the highest-rated brand by scanning with a loop.

You start with:

brands = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"]
ratings = [4, 5, 3, 5, 4]

Build:

1. MegaCorp (5)

Rules:

  • Keep the position of the best brand so far in best_index, starting at 0, and scan the positions from 1 to the end with a loop.
  • Update best_index only on a strictly higher rating. If two brands share the top rating, the one listed first wins (MegaCorp at position 1, not NeoByte at position 3).
  • Format the winner as "1. Brand (rating)" and store it in output.

Walk the positions with for i in range(1, len(ratings)): and compare each rating with the best one so far.

In Python a number must go through str() before it can be joined to text.

brands = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"]
ratings = [4, 5, 3, 5, 4]

best_index = 0
for i in range(1, len(ratings)):
    if ratings[i] > ratings[best_index]:
        best_index = i
output = "1. " + brands[best_index] + " (" + str(ratings[best_index]) + ")"

STEP 1 OF 5
    Ctrl + Enter to check

    PYTHON · LOOPING OVER LIST INDICES

    Top K Brands V3 in Python, explained

    Problem overview

    Version 3 of the brand ranking project handles any number of brands. They are stored in two parallel lists: brands and ratings, where ratings[i] is the rating of brands[i]. The program finds the highest-rated brand with a loop and stores a ranked entry in output. If two brands share the top rating, the one listed first wins.

    With the starting data, the ratings are 4, 5, 3, 5 and 4. The top rating, 5, appears twice: MegaCorp is at position 1 and NeoByte at position 3. MegaCorp comes first, so it wins:

    1. MegaCorp (5)

    Approach: track the position of the best so far

    For a list of any length, the idea is to compare ratings repeatedly in a loop. Keep best_index, the position of the best brand seen so far, and start with position 0. Then look at each remaining position, and whenever its rating is strictly higher than the best one's, update best_index.

    The loop stores a position instead of a rating on purpose. A position identifies the brand and the rating at the same time, because both lists use the same index. Storing only the highest rating would give the number but not the brand it belongs to.

    The comparison is strict (>), so a later brand with an equal rating does not take over. That is exactly the tie rule: MegaCorp keeps the lead against NeoByte.

    Step by step

    1. Create best_index = 0. Before looking at anything else, the first brand is the best known one.
    2. Loop over the remaining positions. for i in range(1, len(ratings)) gives i the values 1 up to the last position. Position 0 is already the best so far, so the loop starts at 1. The same i is valid in both lists.
    3. Compare in the loop. Write an if that checks ratings[i] > ratings[best_index].
    4. Update the best. Inside the if, assign best_index = i.
    5. Format the result after the loop. Build output from "1. ", brands[best_index], " (", str(ratings[best_index]) and ")".

    The solution in Python

    brands = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"]
    ratings = [4, 5, 3, 5, 4]
    
    best_index = 0
    for i in range(1, len(ratings)):
        if ratings[i] > ratings[best_index]:
            best_index = i
    output = "1. " + brands[best_index] + " (" + str(ratings[best_index]) + ")"
    

    Some details worth knowing:

    • range(1, len(ratings)) excludes its end. With five ratings, i takes the values 1, 2, 3 and 4. Those are all the valid positions except 0.
    • The loop leaves i behind. After the loop, i is the last position visited (4 here). Use best_index to read the winner.
    • The formatting line is unindented. It runs once, after the loop. If it were indented under the loop, it would run on every pass and output would only keep the last value.
    • The conversion. The string is a ranked entry in which str() converts the rating, so that + can join it.

    Tracing the example

    The scan begins with best_index = 0 (TechPro, 4). At i = 1, 5 is greater than 4, so best_index becomes 1. At i = 2, 3 is not greater than 5. At i = 3, 5 is not strictly greater than 5, so MegaCorp stays in front. At i = 4, 4 is not greater than 5. The final best_index is 1, which gives 1. MegaCorp (5).

    Edge cases and common mistakes

    • Using >=. NeoByte would replace MegaCorp on the tie, and the output would be 1. NeoByte (5).
    • Starting at 0 in the loop. It works, because the first comparison is a brand against itself, but it adds a pointless step.
    • The best brand is first. With ratings [5, 4, 3], the condition never fires, and best_index stays 0, which is correct.
    • A single brand. range(1, 1) is empty, so the loop does nothing and that brand wins.
    • An empty list. brands[0] would raise an IndexError. The lesson's data always has brands, so it does not check.
    • Saving the rating instead of the index. The loop would then know the top number but not whose it is.

    Testing

    • ratings = [1, 2, 3, 4, 5] gives 1. Zenith (5).
    • ratings = [5, 5, 5, 5, 5] gives 1. TechPro (5), the first of the ties.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free