- Use the
min()
andindex()
Functions to Find the Index of the Minimum Element in a List in Python - Use the
min()
Function andfor
Loop to Find the Index of the Minimum Element in a List in Python - Use the
min()
andenumerate()
Functions to Find the Index of the Minimum Element in a List in Python - Use the
min()
andoperator.itemgetter()
Functions to Find the Index of the Minimum Element in a List in Python - Use the
min()
and__getitem__()
Functions to Find the Index of the Minimum Element in a List in Python - Use the
numpy.argmin()
Function to Find the Index of the Minimum Element in a List in Python - Conclusion
A list object in Python emulates an array and stores different elements under a common name. Elements are stored at a particular index which we can use to access them.
We can perform different operations with a list. It is straightforward to use built-in list functions like max()
, min()
, len
, and more to return the maximum element, smallest element, and list length.
This article will find the minimum element index in a Python list.
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.
A ValueError
is raised if the given element is not in the list.
Example:
lst = [8,6,9,-1,2,0]
m = min(lst)
print(lst.index(m))
Output:
Remember, the index of a list starts from 0. The above answer shows 3 since the smallest element is in the fourth position.
Use the min()
Function and for
Loop to Find the Index of the Minimum Element in a List in Python
We can substitute the use of the index()
function in the previous method with a for
loop. It can iterate over the list and compare elements individually.
When there is a match, we return the value of that index and break out of the loop using the break
statement.
Example:
lst = [8,6,9,-1,2,0]
m = min(lst)
for i in range(len(lst)):
if(lst[i]==m):
print(i)
break
Output:
Use the min()
and enumerate()
Functions to Find the Index of the Minimum Element in a List in Python
The enumerate()
function accepts an iterable. It returns an object containing the elements of the iterable with a counter variable for the element index.
This object can be iterated using a for
loop. Then, we will iterate over this object using list comprehension, create a new list, and use the min()
function to locate the minimum element in a list.
We will get the element and its index in one line.
Example:
lst = [8,6,9,-1,2,0]
a,i = min((a,i) for (i,a) in enumerate(lst))
print(i)
Output:
Use the min()
and operator.itemgetter()
Functions to Find the Index of the Minimum Element in a List in Python
The operator module in Python provides additional operators which we can use to simplify our code. The itemgetter()
function from this module returns a callable object and can retrieve some element from its operand.
The min()
function accepts a key
parameter to determine the criteria for the comparison. We can provide the itemgetter()
function as the value for this parameter to return the index of the minimum element.
Example:
from operator import itemgetter
lst = [8,6,9,-1,2,0]
i = min(enumerate(lst), key=itemgetter(1))[0]
print(i)
Output:
We first find the minimum element and its index in the previous methods. This method does both these steps in one line; therefore, it is considered a faster approach.
Use the min()
and __getitem__()
Functions to Find the Index of the Minimum Element in a List in Python
The operator.itemgetter()
function calls the magic function __getitem__()
internally. We can avoid the need for importing the operator module by directly working with this function and improving the speed of the code.
It is similar to the previous method to return the minimum element index in a list in Python.
Example:
lst = [8,6,9,-1,2,0]
i = min(range(len(lst)), key=lst.__getitem__)
print(i)
Output:
Use the numpy.argmin()
Function to Find the Index of the Minimum Element in a List in Python
The numpy.argmin()
function is used to find the position of the smallest element in Python. We can use this function with lists, and it will return an array with the indices of the minimum element of the list.
Example:
import numpy as np
lst = [8,6,9,-1,2,0]
i = np.argmin(lst)
print(i)
Output:
Conclusion
To wrap up, we discussed several methods to find the index of the minimum element in a list. The min()
function was the most common among all the methods.
Different functions like enumerate()
, itemgetter()
, and more can be used to create different approaches. The final method, using the numpy.argmin()
function, is more straightforward.
I need to find the index of more than one minimum values that occur in an array. I am pretty known with np.argmin
but it gives me the index of very first minimum value in a array. For example.
a = np.array([1,2,3,4,5,1,6,1])
print np.argmin(a)
This gives me 0, instead I am expecting, 0,5,7.
Thanks!
asked Oct 23, 2013 at 16:09
2
This should do the trick:
a = np.array([1,2,3,4,5,1,6,1])
print np.where(a == a.min())
argmin doesn’t return a list like you expect it to in this case.
answered Oct 23, 2013 at 16:21
Tom SwiftyTom Swifty
2,8342 gold badges16 silver badges25 bronze badges
2
Maybe
mymin = np.min(a)
min_positions = [i for i, x in enumerate(a) if x == mymin]
It will give [0,5,7].
answered Oct 23, 2013 at 16:20
tonjotonjo
1,3761 gold badge14 silver badges27 bronze badges
2
I think this would be the easiest way, although it doesn’t use any fancy numpy function
a = np.array([1,2,3,4,5,1,6,1])
min_val = a.min()
print "min_val = {0}".format(min_val)
# Find all of them
min_idxs = [idx for idx, val in enumerate(a) if val == min_val]
print "min_idxs = {0}".format(min_idxs)
answered Oct 23, 2013 at 16:26
jrk0414jrk0414
1441 gold badge1 silver badge11 bronze badges
Ильгиз95 0 / 0 / 2 Регистрация: 13.02.2013 Сообщений: 69 |
||||
1 |
||||
Поиск минимального элемента и его индекса в массиве09.01.2017, 21:05. Показов 18038. Ответов 6 Метки нет (Все метки)
всем привет!
0 |
nd2 3434 / 2813 / 1249 Регистрация: 29.01.2016 Сообщений: 9,426 |
||||
09.01.2017, 21:08 |
2 |
|||
Индексация массивов с 0 начинается.
1 |
STArSka 146 / 27 / 13 Регистрация: 21.09.2015 Сообщений: 62 |
||||
09.01.2017, 21:12 |
3 |
|||
1 |
nd2 3434 / 2813 / 1249 Регистрация: 29.01.2016 Сообщений: 9,426 |
||||
09.01.2017, 21:16 |
4 |
|||
Сообщение было отмечено Ильгиз95 как решение Решение
1 |
Ильгиз95 0 / 0 / 2 Регистрация: 13.02.2013 Сообщений: 69 |
||||
09.01.2017, 21:19 [ТС] |
5 |
|||
спасибо, маленькие недочеты благодаря вам увидел
cout <<
0 |
STArSka 146 / 27 / 13 Регистрация: 21.09.2015 Сообщений: 62 |
||||
09.01.2017, 21:28 |
6 |
|||
Простите, я был невнимателен, проглядел необходимость вывода индекса, вот так — работает
1 |
0 / 0 / 0 Регистрация: 11.04.2022 Сообщений: 3 |
|
18.04.2022, 09:38 |
7 |
Спасибо
0 |
Время чтения 2 мин.
Если вы работаете над проектами по машинному обучению, вам может понадобиться найти максимальное или минимальное значение или индексы в массиве numpy. Вот тут-то и появляется библиотека numpy.
Содержание
- Что такое функция np.argmin() в Python?
- Синтаксис
- Параметры
- Возвращаемое значение
- Нахождение индекса минимального элемента одномерного массива
- Нахождение индексов максимальных элементов многомерного массива
Функция numpy.argmin() используется в Python для получения индексов минимального элемента из массива (одномерный массив) или любой строки или столбца (многомерный массив) любого заданного массива. Функция numpy argmin() принимает arr, axis и out в качестве параметров и возвращает массив.
Синтаксис
numpy.argmin(arr,axis=None,out=None) |
Параметры
Функция numpy argmin() принимает три аргумента:
- arr: массив, из которого мы хотим получить индексы минимального элемента.
- axis: по умолчанию это None. Но для многомерного массива, если мы собираемся найти индекс любого максимума элемента по строкам или по столбцам, мы должны указать axis = 1 или axis = 0 соответственно.
- out: если указано, результат будет вставлен в этот массив. Он должен быть соответствующей формы и типа.
Возвращаемое значение
Функция np.argmin() возвращает массив, содержащий индексы минимальных элементов.
Нахождение индекса минимального элемента одномерного массива
См. следующий код.
#Importing numpy import numpy as np #We will create an 1D array arr = np.array([4, 24, 63, 121, 4, 64]) #Printing the array print(«The array is: «, arr) #Shape of the array print(«Shape of the array is : «, np.shape(arr)) #Now we will print index of min value of this array print(«Index of minimum value of the given array is: «, np.argmin(arr)) |
Выход
The array is: [ 4 24 63 121 4 64] Shape of the array is : (6,) Index of minimum value of the given array is: 0 |
Объяснение.
В этой программе мы сначала объявили массив с некоторыми случайными числами, заданными пользователем. Затем мы напечатали форму(размер) массива. Затем мы вызвали функцию argmin(), чтобы получить индекс минимального элемента из массива. Мы видим, что минимальный элемент этого массива равен 4, который находится в позиции 0, поэтому выход равен 0.
Нахождение индексов максимальных элементов многомерного массива
См. следующий код.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#Importing numpy import numpy as np #We will create a 2D array #Of shape 4×3 arr = np.array([(1, 9, 4),(6, 55, 4),(1, 3, 40),(5, 6, 4)]) #Printing the array print(«The array is: «) print(arr) print(«Shape of the array is: «, np.shape(arr)) #Now we will find the indices of minimum value for some cases #Indices of minimum value of each row a = np.argmin(arr, axis=1) print(«Indices of minimum value of each row of the array is: «, a) #Indices of minimum value of each column b = np.argmin(arr, axis=0) print(«Indices of minimum value of each column of the array is: «, b) |
Выход
The array is: [[ 1 9 4] [ 6 55 4] [ 1 3 40] [ 5 6 4]] Shape of the array is: (4, 3) Indices of minimum value of each row of the array is: [0 2 0 2] Indices of minimum value of each column of the array is: [0 2 0] |
Объяснение.
В этой программе мы сначала объявили матрицу размера 4×3; вы также можете увидеть форму матрицы, которая равна(4,3). Затем мы вызвали argmin(), чтобы получить вывод о различных случаях.
Sometimes, while working with Python lists, we can have a problem in which we intend to find the position of minimum element of list. This task is easy and discussed many times. But sometimes, we can have multiple minimum elements and hence multiple minimum positions. Let’s discuss ways to achieve this task.
Method #1: Using min() + enumerate() + list comprehension In this method, the combination of above functions is used to perform this particular task. This is performed in two steps. In 1st, we acquire the minimum element and then access the list using list comprehension and corresponding element using enumerate and extract every element position equal to minimum element processed in step 1.
Python3
test_list
=
[
2
,
5
,
6
,
2
,
3
,
2
]
print
("The original
list
: "
+
str
(test_list))
temp
=
min
(test_list)
res
=
[i
for
i, j
in
enumerate
(test_list)
if
j
=
=
temp]
print
("The Positions of minimum element : "
+
str
(res))
Output :
The original list : [2, 5, 6, 2, 3, 2] The Positions of minimum element : [0, 3, 5]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2: Using loop + min() This is brute method to perform this task. In this, we compute the minimum element and then iterate the list to equate to min element and store indices.
Python3
test_list
=
[
2
,
5
,
6
,
2
,
3
,
2
]
print
("The original
list
: "
+
str
(test_list))
temp
=
min
(test_list)
res
=
[]
for
idx
in
range
(
0
,
len
(test_list)):
if
temp
=
=
test_list[idx]:
res.append(idx)
print
("The Positions of minimum element : "
+
str
(res))
Output :
The original list : [2, 5, 6, 2, 3, 2] The Positions of minimum element : [0, 3, 5]
Time Complexity: O(n*n), where n is the length of the input list. This is because we’re using the loop which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.
Approach 3: Using numpy
Note: Install numpy module using command “pip install numpy”
The numpy.where() function returns the indices of elements in an array that satisfy a given condition. In this case, the condition is test_list == np.min(test_list), which returns a Boolean array with True at the indices where the elements are equal to the minimum element in the list, and False elsewhere. The [0] at the end is used to extract the indices from the output of numpy.where(), which is a tuple containing the indices in the first element.
Python3
import
numpy as np
test_list
=
[
2
,
5
,
6
,
2
,
3
,
2
]
print
(
"The original list : "
+
str
(test_list))
res
=
np.where(test_list
=
=
np.
min
(test_list))[
0
]
print
(
"The Positions of minimum element : "
+
str
(res))
Output:
The original list : [2, 5, 6, 2, 3, 2] The Positions of minimum element : [0 3 5]
Time complexity: O(n)
Auxiliary Space: O(n)
Method 4: Use a dictionary to store the indices of each unique value in the list.
Step-by-step approach
- Define the input list test_list with some integer values.
- Print the input list using print().
- Find the minimum value in the list using the min() function, and store it in the variable min_val.
- Create an empty dictionary index_dict to store the indices of each unique value in the list.
- Loop through the elements in test_list using the enumerate() function to get both the index and value at each position in the list.
- Check if the current value is already in index_dict. If it is not, add a new key-value pair to the dictionary where the key is the value and the value is a list
- containing the current index. If the value is already in the dictionary, append the current index to the list of indices for that value.
- Retrieve the list of indices for the minimum value from index_dict and store it in the variable res.
- Print the list of indices of the minimum element in the original list using print().
Below is the implementation of the above approach:
Python3
test_list
=
[
2
,
5
,
6
,
2
,
3
,
2
]
print
(
"The original list : "
+
str
(test_list))
min_val
=
min
(test_list)
index_dict
=
{}
for
i, x
in
enumerate
(test_list):
if
x
not
in
index_dict:
index_dict[x]
=
[i]
else
:
index_dict[x].append(i)
res
=
index_dict[min_val]
print
(
"The Positions of minimum element : "
+
str
(res))
Output
The original list : [2, 5, 6, 2, 3, 2] The Positions of minimum element : [0, 3, 5]
Time complexity: O(n), where n is the length of the list, because it loops through the list once to build the dictionary and once to retrieve the indices of the minimum value.
Auxiliary space: O(m), where m is the number of unique values in the list, because the dictionary can potentially store indices for each unique value in the list.
Last Updated :
17 Apr, 2023
Like Article
Save Article