Categories
Python Answers

How to get the index of the returned max or min item using max()/min() on a list with Python?

Spread the love

Sometimes, we want to get the index of the returned max or min item using max()/min() on a list with Python.

In this article, we’ll look at how to get the index of the returned max or min item using max()/min() on a list with Python.

How to get the index of the returned max or min item using max()/min() on a list with Python?

To get the index of the returned max or min item using max()/min() on a list with Python, we can use the values.__getitem__ method as the value of the key parameter of min.

For instance, we write:

values = [1, 2, 3, 4, 5]
index_min = min(range(len(values)), key=values.__getitem__)
print(index_min)

We call min with range(len(values)) to get the min index of the item with the lowest value in the values list.

And we set key to values.__getitem__ to get the value from the index in the range(len(values)) generator so we can use the values in the values list for comparison.

Therefore, index_min is 0.

Conclusion

To get the index of the returned max or min item using max()/min() on a list with Python, we can use the values.__getitem__ method as the value of the key parameter of min.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *