Как найти номер минимального элемента массива питон

In this tutorial, we will look at how to find the min value in a Python list and its corresponding index with the help of some examples.

How to get the minimum value in a list in Python?

A simple approach is to iterate through the list and keep track of the minimum value. Alternatively, you can also use the Python built-in min() function to find the minimum value in a list.

minimum value in a list

Let’s look at some of the different ways of finding the smallest value and its index in a list.

Loop through the list to find the minimum

Iterate through the list values and keep track of the min value. Here’s an example.

# create a list
ls = [3, 6, 7, 2, 1, 5]

# find min value using loop
min_val = ls[0]
for val in ls:
    if val < min_val:
        min_val = val
# display the min value
print(min_val)

Output:

1

Here, we iterate over each value in the list ls and keep track of the minimum value encountered in the variable min_val. After the loop finishes, the variable min_val stores the minimum value present in the list, 1.

You can use this method to get the index corresponding to the minimum value in the list as well. Use an additional variable to keep track of the current minimum value’s index.

# create a list
ls = [3, 6, 7, 2, 1, 5]

# find min value using loop
min_val = ls[0]
min_val_idx = 0
for i in range(len(ls)):
    if ls[i] < min_val:
        min_val = ls[i]
        min_val_idx = i
    
# display the min value
print(min_val)
# display its index
print(min_val_idx)

Output:

1
4

We get the minimum value and its index after the loop finishes. Here we iterate through the list via its index rather than the values. You can also use the enumerate() function to iterate through the index and value together.

Using min() to get the maximum value

You can also use the Python built-in min() function to get the min value in a list. The function returns the minimum value in the passed iterable (for example, list, tuple, etc.).

# create a list
ls = [3, 6, 7, 2, 1, 5]
# find min value
min(ls)

Output:

1

Using the min() function is simple and is just a single line code compared to the previous example.

You can use the list index() function to find the index corresponding to the minimum value (assuming you already know the minimum value).

# create a list
ls = [3, 6, 7, 2, 1, 5]

# find min value
min_val = min(ls)
# display the min value
print(min_val)
# display its index
print(ls.index(min_val))

Output:

1
4

We get the min value and its index in the list ls.

Note that the list index() function returns the index of the first occurrence of the passed value. If the min value occurs more than once in the list, you’ll only get the index of its first occurrence. You can use list comprehension to get all the indices of occurrence of the min value in the list.

# create a list
ls = [3, 6, 1, 2, 1, 5]

# find min value
min_val = min(ls)
print(min_val)
# find all indices corresponding to min val
min_val_idx = [i for i in range(len(ls)) if ls[i]==min_val]
print(min_val_idx)

Output:

1
[2, 4]

We get all the indices where the minimum value occurs in the list ls.

You might also be interested in –

  • Find Mode of List in Python
  • Python – Get median of a List

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

    View all posts

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

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!

Saullo G. P. Castro's user avatar

asked Oct 23, 2013 at 16:09

user2766019's user avatar

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 Swifty's user avatar

Tom SwiftyTom Swifty

2,8242 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

tonjo's user avatar

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

jrk0414's user avatar

jrk0414jrk0414

1441 gold badge1 silver badge11 bronze badges

  1. Use the min() and index() Functions to Find the Index of the Minimum Element in a List in Python
  2. Use the min() Function and for Loop to Find the Index of the Minimum Element in a List in Python
  3. Use the min() and enumerate() Functions to Find the Index of the Minimum Element in a List in Python
  4. Use the min() and operator.itemgetter() Functions to Find the Index of the Minimum Element in a List in Python
  5. Use the min() and __getitem__() Functions to Find the Index of the Minimum Element in a List in Python
  6. Use the numpy.argmin() Function to Find the Index of the Minimum Element in a List in Python
  7. Conclusion

Find Index of Minimum Element in a List in Python

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.

На чтение 2 мин Просмотров 721 Опубликовано 17.03.2023

Содержание

  1. Введение
  2. Метод sort()
  3. Метод sorted()
  4. Циклом for
  5. Функция min()
  6. Заключение

Введение

В статье рассмотрим четыре способа найти минимальное число в списке в Python.

Метод sort()

Данный способ заключается в том, что мы отсортируем список методом sort(), и минимальное число окажется в самом начале последовательности:

new_list = [6, 10, 5, 2, 7]
new_list.sort()

print(f'Минимальное число в списке: {new_list[0]}')

# Вывод: Минимальный элемент в списке: 2

Метод sorted()

По сути этот способ работает по той же методике, что и предыдущий. Различие лишь в том, что мы будем использовать метод sorted():

new_list = [6, 10, 5, 2, 7]
new_list = sorted(new_list)

print(f'Минимальное число в списке: {new_list[0]}')

# Вывод: Минимальный элемент в списке: 2

Циклом for

Определить минимальное число в списке можно также при помощи цикла for. Для этого создадим переменную min_number, и сохраним в неё значение первого элемента списка:

new_list = [6, 10, 5, 2, 7]
min_number = new_list[0]

Теперь создадим цикл, в котором пройдёмся по всему списку new_list. Внутри цикла зададим условие, что если итерабельное значение меньше min_number, то меняем значение в min_number на итерабельное:

new_list = [6, 10, 5, 2, 7]
min_number = new_list[0]

for i in new_list:
    if i < min_number:
        min_number = i

print(f'Минимальное число в списке: {min_number}')

# Вывод: Минимальный элемент в списке: 2

Функция min()

В Python есть специальная встроенная функция для нахождения минимального значения не только в списке, но и в кортеже со строкой.

Просто сохраним минимальное значение в переменную min_number, и выведем:

new_list = [6, 10, 5, 2, 7]
min_number = min(new_list)

print(f'Минимальное число в списке: {min_number}')

# Вывод: Минимальный элемент в списке: 2

Заключение

В ходе статьи мы с Вами разобрали целых четыре способа, благодаря которым можно найти минимальный элемент в списке Python. Надеюсь Вам понравилась статья, желаю удачи и успехов! 🙂

Admin

Добавить комментарий