Функции min() и max() в Python
Функция min() в Python возвращает наименьший элемент в итерации или наименьший из двух или более аргументов.
Синтаксис функции min():
- Если есть только один аргумент, он должен быть итерируемым, таким как строка, список, кортеж и т.д. возвращается наименьший элемент в итерируемом объекте.
- Если предоставлено два или более аргумента, будет возвращен наименьший из них.
- Мы можем указать функцию ключевого аргумента, которая будет использоваться для определения наименьшего элемента. Это необязательный аргумент и в основном используется, когда аргументы являются настраиваемыми объектами.
- Аргумент по умолчанию указывает объект, который нужно вернуть, если предоставленный итеративный объект пуст. Если итерируемый объект пуст и значение по умолчанию не указано, возникает исключение ValueError.
- Если найдено несколько наименьших элементов, возвращается первый.
Примеры функции min
Давайте посмотрим на несколько примеров функции min() в python .
Min со строкой
Когда функция min() используется со строковым аргументом, возвращается символ с минимальным значением Unicode.
Я использую функцию ord() для печати кодовой точки Unicode символов в строке.
Min с кортежем
Min со списком
С настраиваемыми объектами
Когда мы хотим использовать функцию min() с настраиваемыми объектами, мы должны предоставить ключевой аргумент функции, который будет использоваться для сравнения объектов.
Вывод: Данные [-10].
Если мы не предоставим ключевую функцию в качестве аргумента, мы получим следующую ошибку.
С пустой итерацией и значением по умолчанию
С несколькими аргументами
С аргументами и ключевой функцией
Обратите внимание, что и «a», и «b» являются наименьшими аргументами, поэтому первый «a» возвращается функцией min().
С несколькими итерациями
Если мы не предоставим ключевую функцию в качестве аргумента, вывод будет [5, 15, 40, 25]. Это потому, что сравнение будет выполняться между элементами повторяющихся элементов один за другим. Когда будет найден элемент с меньшим значением, будет возвращена итерация с этим элементом.
С несколькими итерациями объектов
Обратите внимание, что с несколькими аргументами итерации обрабатываются как объекты. Если мы не укажем ключевую функцию, мы получим сообщение об ошибке, как TypeError: ‘. Раньше он работал с целочисленными элементами, потому что они поддерживают операторы > and <.
Функция min() в Python помогает нам идентифицировать наименьший элемент в повторяемом или наименьшем элементе из нескольких аргументов. Это полезно, потому что мы можем указать нашу собственную функцию, которая будет использоваться для сравнения с помощью ключевого аргумента. Это противоположность функции python max().
Функция max() в Python возвращает самый большой элемент в итерируемом или самый большой из двух или более аргументов.
Синтаксис функции max():
- Если есть только один аргумент, он должен быть итерируемым, таким как строка, список, кортеж и т.д. Возвращается самый большой элемент в итерации.
- Если предоставлено два или более аргумента, будет возвращен самый большой из них.
- Мы можем указать функцию ключевого аргумента, которая будет использоваться для определения самого большого элемента. Это необязательный аргумент и в основном используется, когда аргументы являются настраиваемыми объектами.
- Аргумент по умолчанию указывает объект, который нужно вернуть, если предоставленный итеративный объект пуст. Если итерируемый объект пуст и значение по умолчанию не указано, возникает исключение ValueError.
- Если найдено несколько наибольших элементов, возвращается первый.
Давайте посмотрим на несколько примеров функции max().
Max со строкой
Когда функция max() используется со строковым аргументом, возвращается символ с максимальным значением Unicode.
Max с кортежем
Max list
Max с настраиваемыми объектами
Когда мы хотим использовать функцию max() с настраиваемыми объектами, мы должны предоставить ключевой аргумент функции, который будет использоваться для сравнения объектов.
Если мы не предоставим ключевую функцию в качестве аргумента, мы получим следующую ошибку.
С пустой итерацией и значением по умолчанию
С несколькими аргументами
С аргументами и ключевой функцией
С несколькими итерациями
Вывод: [5, 15, 40, 25].
Если мы не предоставим ключевую функцию в качестве аргумента, вывод будет [10, 20, 30]. Это потому, что сравнение будет выполняться между элементами один за другим. Когда будет найден элемент с большим значением, будет возвращена итерация с этим элементом.
С несколькими итерациями объектов
Обратите внимание, что итерации с несколькими аргументами обрабатываются как объекты. Если мы не укажем ключевую функцию, мы получим сообщение об ошибке как TypeError: ‘>’ не поддерживается между экземплярами ‘Data’ и ‘Data’. Раньше он работал с целочисленными элементами, потому что они поддерживают операторы > and <.
Резюме
Функция Python max() помогает нам идентифицировать самый большой элемент в повторяемом или самом большом элементе из нескольких аргументов. Это полезно, потому что мы можем указать нашу собственную функцию, которая будет использоваться для сравнения с помощью ключевого аргумента.
Как найти минимальное число в питоне
This article brings you a very interesting and lesser-known function of Python, namely max() and min(). Now when compared to their C++ counterpart, which only allows two arguments, that too strictly being float, int or char, these functions are not only limited to 2 elements, but can hold many elements as arguments and also support strings in their arguments, hence allowing to display lexicographically smallest or largest string as well. Detailed functionality are explained below.
This function is used to compute the maximum of the values passed in its argument and lexicographically largest value if strings are passed as arguments.
Python min() Function
Summary: in this tutorial, you’ll learn how to use the Python min() function to return the smallest item of an iterable or the smallest argument of two or more arguments.
Introduction to the Python min() function
The min() function returns the smallest items of two or more arguments:
- arg1 , arg2 , .. are the input arguments.
- key is an optional keyword-only parameter that specifies a key for comparing the arguments.
The min() function also accepts an iterable and returns the smallest item of the iterable:
- iterable is the input iterable.
- key is an optional keyword-only argument that specifies the key for comparing the items of the iterable.
- default is an optional keyword-only argument that specifies a value that the min() function returns if the iterable is empty. If the iterable is empty and the default argument is omitted, the min() function raises a ValueError exception.
If multiple items are minimal, the min() function returns the first one it encounters.
Python min() function examples
Let’s take some examples of using the Python min() function.
1) Using the Python min() function to find the minimum argument between multiple arguments
The following example uses the min() function to get the smallest numbers:
If you pass multiple strings, the min() function returns the minimum string based on alphabetical order:
The following example shows how to use the min() function with user-defined objects:
First, define the Person class with two attributes, name and age :
Second, use the min() function to find the person with the smallest age:
Besides passing the Person objects, we also specify the age as the key to comparing these Person objects.
2) Using the Python min() function to find the minimum item of an iterable
The following example uses the min() function to find the smallest number of a list:
Similarly, this example uses the min() function to find the minimum name based on alphabetical order:
This example illustrates how to use the min() function to find the youngest person:
In this example, we pass a list of Person objects and use the min() function to find the youngest person who has the smallest age.
Find Max And Min In A List Python
Working with lists is very common in Python and even more common is to find max and min in a list Python. We will see 3 different methods for each to find min and max in a python list.
A list in python is a collection of user-stored data in order. In a list, data can be of any type like string, integer, float, boolean, etc.
A list can be created by using square brackets [ ] . Example [1, "a", True]
A list can have mixed data or can have only one data type. To find max and min in a list, we will work on a list of numbers. A list that has only integers or float values both negative and positive can be used to find max and min.
Find Maximum Value In List
To find maximum value in a list we will use 3 different methods.
- Using max() function
- Finding the maximum value using for loop
- Using sort() function
1. Using max() function
The max() function is built-in function in Python. It returns the maximum value in a list. It takes a list as an argument and returns the maximum value in the list.
The function accepts the list as an argument. Here is the syntax:
Let's see an example to find the maximum value in a list.
Max in a list of string
The max() function can also be used to find the maximum value in a list of strings.
To compare the values among strings, the max() function uses their ASCII values. For example, the ASCII value of a is 97 and the ASCII value of z is 122.
In the above example, max of the list is e because the ASCII value of e is 101 which is the highest in the list.
Note : max() function does not work on lists of mixed data types.
2. Finding the maximum value using for loop
You can create your own Python function to find the maximum value in a list using for loop and if condition.
Algorithm to find the maximum value in a list
- Create a variable max and assign it to the first element of the list
- Create a for loop to iterate over the list
- Check if the current element is greater than max , if yes then assign it to max . Now current element will become the new max .
- Keep iterating over the list until the end of the list and return max .
The example below is implemented using the above algorithm.
The above example will find the maximum value in the list and print it.
3. Using sort() function: find max
The sort() function is another built-in function in python using which we can find the maximum value in a list. The sort() function sorts the list in ascending order, which means smallest stays at the first position and largest stays at the last position.
The sort() function takes a list as an argument. TO get the maximum value in a list, you can sort the list and picks the last element of the list.
The above example sorts the list and then picks the last element from the sorted list which is the maximum value in the list.
report this ad
Find Minimum Value In List
Again to find the minimum from a list we can use similar 3 methods but this time just to find the minimum value.
- Using min() function
- Finding the minimum value using for loop
- Using sort() function
1. Using min() function
The min() function in python finds the minimum value from a list and returns it. It can work with both numbers and strings as well but not with mixed data types.
In the following example, the min() function finds the minimum value in a list of numbers and prints the output.
Min in a list of string
The min() function can also find the minimum value in a list of strings by comparing their ASCII values.
2. Finding the minimum value using for loop
Creating own function to find minimum value in a list by comparing one value to each other.
Algorithm to find the minimum value in a list
- Store the first element of the list in a variable min
- Now loop through the list element and compare elements from each other. If the current element is less than min , then assign it to min . Now you have the new min value.
- Keep repeating the above steps until the end of the list. At the last min variable will have the actual minimum value of the string.
- Return min .
Here is the implementation of the above algorithm.
The function will find the minimum value in the list and returns it as output.
3. Using sort() function : find min
We can again use the sort() function here to sort the elements of a list in ascending order and then picks the first element of the list which is the minimum value.
The sort() method sorted the element in ascending order which puts the smallest value in the list at the first position which is -28.
Conclusions
In this short guide, we have covered 3 methods for each to find max and min in a list python. We have also covered the min(), max() and sort() as in-built functions in python and also created a custom function to find minimum and maximum.
Stay Ahead, Learn More
report this ad