Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.

enumerate: Index and Value Together

~9 mincode completion

Sometimes you need both the position and the value. The clumsy way is to loop over indices and index back in:

for i in range(len(names)):
    print(i, names[i])

enumerate does it directly, and this is the version experienced Python programmers write:

for i, name in enumerate(names):
    print(i, name)

It hands you a pair each time round, which you unpack into two variables. Indices start at 0. If you want them to start at 1, pass start=1.

Finding the position of the largest value is a classic use. You track both the best value seen so far and where it was:

best_i = 0
for i, value in enumerate(values):
    if value > values[best_i]:
        best_i = i

Your task:

Write index_of_largest(values) that returns the index of the largest value in the list. If the largest value appears more than once, return the index of the first one. Assume the list is not empty.

[4, 9, 2, 9] returns 1.

Example Tests

Returns the index, not the value itself

Input: {"values":[4,9,2,7]}

Expected: 1

When the largest value repeats, the earliest index wins

Input: {"values":[4,9,2,9]}

Expected: 1

The largest can be the first item

Input: {"values":[10,1,2]}

Expected: 0

Python
def index_of_largest(values):
    """
    Find the position of the largest value.

    Args:
        values: a non-empty list of numbers

    Returns:
        The index of the largest value. Ties go to the earliest one.
    """
    # YOUR CODE HERE
    pass

Run your code to see results

⌘↵ runs against the visible tests

Loading docs…