Say I have a list of numbers [ 20, 15, 27, 30 ]
How would I return the index number of the smallest value in this list. (15
) Obviously, min(lst) will return the smallest number itself, but how do I instead return it's index "1
" ?
Method #1 : Using loop + set() In this, we just insert all the elements in set and then compare each element's existence in actual list. If it's the second occurrence or more, then index is added in result list.
Use min() and list. index() Functions to Get the Smallest Index of the List. In Python, the min() method will return the smallest value of the defined list. The smallest index of the element in the list is returned by the l.
Use the min() and index() Functions to Find the Index of the Minimum Element in a List in Python. In Python, we can use the min() function to find the smallest item in the iterable. Then, the index() function of the list can return the index of any given element in the list.
Since you already know how to find the minimum value, you simply feed that value to the index()
function to get the index of this value in the list. I.e,
n = [20, 15, 27, 30]
n.index(min(n))
yields
1
This will return the index of the minimum value in the list. Note that if there are several minima it will return the first.
min(): With a single argument iterable, return the smallest item of a non-empty iterable (such as a string, tuple or list). With more than one argument, return the smallest of the arguments.
list.index(x): Return the index in the list of the first item whose value is x. It is an error if there is no such item.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With