Getting the index of the returned max or min item using max()/min() on a list

You can use the enumerate() function along with max() or min() to get the index of the maximum or minimum item in a list in Python. Here's an example:

my_list = [3, 6, 1, 8, 4, 9]

# To get the index of the maximum item
max_index = max(enumerate(my_list), key=lambda x: x[1])[0]
print(max_index)  # Output: 5

# To get the index of the minimum item
min_index = min(enumerate(my_list), key=lambda x: x[1])[0]
print(min_index)  # Output: 2

Watch a course Python - The Practical Guide

In this example, enumerate(my_list) returns a list of tuples, where each tuple is of the form (index, item). The key argument of max() and min() is used to specify the function to extract the value used for comparison from each tuple. In this case, we want to compare the second element of each tuple (i.e., the item), so we use the lambda function lambda x: x[1]. The final result is the tuple containing the index and the max or min value, so we use [0] to extract the index.