Python Min



The min function returns the item with the lowest value, or the item with the lowest value in an iterable. If the values are strings, an alphabetically comparison is done. Min This function is used to compute the minimum of the values passed in its argument and lexicographically smallest value if strings are passed as arguments. Worked in sequence presents as numbers as well as None. If all values is None min raise exception. ValueError: min arg is an empty sequence. This code resolve this problem at all. Pros: Worked if None presents in sequence; Worked on Python 3; max will be work also; Cons. Need more than one non-zero variable in the list. In this article, we will learn more about Min Heap (known as heap queue in Python). We have already learned about Heap and its library functions (in heapq module) in python. We will now learn about min-heap and its implementation and then look at the Python code for implementing the heapify, heappush and heappop functions ourselves.

While programming in Python, it is common to work with data structures such as lists and tuples. If you perform operations using elements of a list, it is possible that you will have to determine the highest or lowest value among the elements. For this, Python offers two methods – max() and min().

What is Python min()?

The Python min() function is used to find the smallest element of iterable or two or more arguments.

min() function can be used with List / Array, Tuple, Sets & Dictionary

Syntax

Parameters

  • x,y,z… (required): multiple items to compare
  • Iterable : (required) string, list, tuple etc

Return Value

Returns the minimum of all the arguments.

Exceptions

Returns Error when conflict with arguments passed.

key (optional): Key is the name of the function to which arguments or iterable is passed and the comparison is done based on the value returned by this function.

Example

Output:

Explanation

Min

The first line print('The Minimum is: ', min(44, 2, 34, 12)), checks the minimum value among the numbers. As the lowest number among the mentioned numbers is 2, it is printed to the screen. The second line checks the smallest string among the ones mentioned. Among the strings 'Apple', 'banana', 'greps'; the string which alphabetically comes first is Apple. So, the min() method considers this string as the minimum. The string Apple is printed to the screen as a result.

min() Function with Array / List

Example

Output

Explanation

Here, an integer list called listInt is initialized with the elements [1, 33, 2, 23, 7, -4, 22, 222, 44, 232, 2]. Then a string list called listText is initialized with the elements ['Apple', 'Banana', 'Grapes', 'Orange','Pears']. The next line of code, print('The Lowest number in list: ', min(listInt)) prints out the lowest number in the first list of integers. Similarly, the lowest string is printed out using the min() method in the next line.

The last line prints the lowest element in the list with the help of a key function that specifies len or length. After program execution, the lowest number -4 is printed at first. Then, the minimum string element Apple is displayed to the user.

min() Function with Tuple

Example

Output

Explanation

In this program, an integer tuple called listtuple is created using the elements (1, 32, 2, 22, 7, -3, 232, 223, 12, 317, 2). Then the tuple is assigned values of strings ('Apple', 'Banana', 'Greps', 'Orange', 'Pears'). In the next line, with the help of a min() method that takes in an argument listtuple, the lowest element of the list is determined. This value is printed out using the print statement.

Then the string elements with the minimum length is printed out in the next statement using the min() method that has a key value of len (length). The final result is the string with the lowest length, Apple. The other print statements also print out Apple as it is the minimum element.

min() Function with Dictionary

Example

Output

Explanation

In this program, a dictionary called listdis is initialized with keys and value pairs of {1:'Apple', 3:'Banana', 2:'Greps', 4:'Orange', 7:'Pears'}. The next print statement displays the minimum value of the dictionary list, by passing the listdis dictionary as argument to the min() method. The min() method checks the lowest key among the key-value pairs within the dictionary. Hence, the lowest key 1 is printed as the final result.

Conclusion

The key parameter is optional, so make sure to specify it properly. While determining the minimum element form a dictionary, make sure there are no syntax errors and the key-value pairs are coded correctly.

Tutorial

The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

Introduction

Python includes a number of built-in functions—these are global Python functions that can be called from any Python code without importing additional modules. For example, you can always call the print built-in function to output text.

Several of the built-in functions (all, any, max, and min among them) take iterables of values as their argument and return a single value. An iterable is a Python object that can be “iterated over”, that is, it will return items in a sequence such that you can use it in a for loop. Built-in functions are useful when, for example, you want to determine if all or any of the elements in a list meet a certain criteria, or find the largest or smallest element in a list.

In this tutorial, you will use the built-in functions all, any, max, and min.

Prerequisites

To get the most out of this tutorial, it is recommended to have:

  • Some familiarity with programming in Python 3. You can review our How To Code in Python 3 tutorial series for background knowledge.

  • The Python Interactive Console, if you would like to try out the example code in this tutorial you can use the How To Work with the Python Interactive Console tutorial.

Using all

The built-in function all checks if every element in an iterable is True. For example:

If you run the previous code, you will receive this output:

Python min function

In this first example, you call all and give it a list with two elements (two True Boolean values). Since every element in the iterable is True, the output was True.

all will return False if one or more elements in the given iterable is False:

If you run the previous code, you’ll receive this output:

You call all with a list containing three elements including one False Boolean value. Since one of the elements in the iterable was False, the output of the call to all was False.

Notably, all stops iterating and immediately returns False as soon as it encounters the first False entry in an iterable. So, all can be useful if you want to check successive conditions that may build on each other, but return immediately as soon as one condition is False.

A special case to be aware of is when all is given an empty iterable:

If you run the previous code, you’ll receive this output:

When you give all an empty iterable (for example, an empty list like all([])), its return value is True. So, all returns True if every element in the iterable is True or there are 0 elements.

all is particularly helpful when combined with generators and custom conditions. Using all is often shorter and more concise than if you were to write a full-fledged for loop. Let’s consider an example to find out whether there are elements in a list that start with 's':

If you run the previous code, you will receive this output:

You call all with a generator as its argument. The generator produces a Boolean for each element in the animals list based on whether or not the animal starts with the letter s. The final return value is True because every element in the animals list starts with s.

Note: You can often use Generator expressions in place of list comprehensions as a way of saving memory. For example, consider all(i < 8 for i in range(3)) and all([i < 8 for i in range(3)]). Both statements return True because 0, 1, 2 are all less than 8. Dead samurai 2another unblocked game site. The second example (which uses a list comprehension), however, has the added overhead of implicitly creating a list three entries long ([True, True, True]) and then passing that list to the all function. The first example (which uses generator expressions), by contrast, passes a generator object to the all function, which the all function iterates over directly without the overhead of an intermediary list.

Consider that the equivalent code written using a full-fledged for loop would have been significantly more verbose:

Without all, your code for determining if all the animals start with the letter s requires several more lines to implement.

Next, you’ll look at the sibling function to all: any.

Python Min

Using any

You can use the built-in function any to check if any element in an iterable is True. For example:

If you run the previous code, you’ll receive this output:

You call any and give it a list with two elements (a False Boolean value and a True Boolean value). Since one or more element in the iterable was True, the output was also True.

any will return False if, and only if, 0 of the elements in the given iterable are True:

If you run the previous code, you’ll receive this output:

You call any with a list containing three elements (all False Boolean values). Since 0 of the elements in the iterable is True, the output of the call to any is False.

Notably, any stops iterating and immediately returns True as soon as it encounters the first True entry in an iterable. So, any can be useful if you want to check successive conditions, but return immediately as soon as one condition is True.

any—like its sibling method all—is particularly helpful when combined with generators and custom conditions (in place of a full for loop). Let’s consider an example to find out whether there are elements in a list that end with 'urchin':

You will receive this output:

You call any with a generator as its argument. The generator produces a Boolean for each element in the animals list based on whether or not the animal ends with urchin. The final return value is True because one element in the animals list ends with urchin.

Note: When any is given an empty iterable (for example, an empty list like any([])), its return value is False. So, any returns False if there are 0 elements in the iterable or all the elements in the iterable are also False.

Next, you’ll review another built-in function: max.

Using max

The built-in function max returns the largest element given in its arguments. For example:

max is given a list with four integers as its argument. The return value of max is the largest element in that list: 8.

The output will be the following:

If given two or more positional arguments (as opposed to a single positional argument with an iterable), max returns the largest of the given arguments:

If you run the previous code, you will receive this output:

max is given three individual arguments, the largest of which being 3. So, the return value of the call to max is 3.

Just like any and all, max is particularly helpful because it requires fewer lines to use than equivalent code written as a full for loop.

max can also deal with objects more complex than numbers. For example, you can use max with dictionaries or other custom objects in your program. max can accommodate these objects by using its keyword argument named key.

You can use the key keyword argument to define a custom function that determines the value used in the comparisons to determine the maximum value. For example:

The output will be the following:

You call max with a list of dictionaries as its input. You give an anonymous lambda function as the key keyword argument. max calls the lambda function for every element in the entries list and returns the value of the 'id' key of the given element. The final return value is the second element in entries: {'id': 17}. The second element in entries had the largest 'id' value, and so was deemed to be the maximum element.

Note that when max is called with an empty iterable, it refuses to operate and instead raises a ValueError:

If you run this code, you will receive the following output:

You call max with an empty list as its argument. max does not accept this as a valid input, and raises a ValueError Exception instead.

max has a counterpart called min, which you’ll review next.

Using min

The built-in function min returns the smallest element given in its arguments. For example:

You give min a list with four integers as its argument. The return value of min is the smallest element in that list: 0.

The output will be:

If given two or more positional arguments (as opposed to a single positional argument with an iterable), min returns the smallest of the given arguments:

If you run the previous code, you will receive this output:

You give min three individual arguments, the smallest of which being -1. So, the return value of the call to min is -1.

Like max, min supports the keyword argument named key so that you can pass objects more complex than numbers into it. Using the key argument allows you to use the min function with any custom objects your program might define.

You can use the key keyword argument to define a custom function that determines the value used in the comparisons to determine the minimum value. For example:

You call min with a list of dictionaries as its input. You give an anonymous lambda function as the key keyword argument. min calls the lambda function for every element in the entries list and returns the value of the 'id' key of the given element. The final return value is the third element in entries: {'id': 4}. The third element in entries had the smalled 'id' value, and so was deemed to be the minimum element.

Like max, when you call min with an empty iterable, it refuses to operate and instead raises a ValueError:

If you run the previous code, you will receive this output:

You call min with an empty list as its argument. min does not accept this as a valid input, and raises a ValueError Exception instead.

Conclusion

Python Min Heap

In this tutorial, you used the Python built-in functions all, any, max, and min. You can learn more about the functions all, any, max, and min and other Python built-in in the Python docs.

Python Min Max

For more information on other Python built-ins, you can also check out Built-in Python 3 Functions for Working with Numbers, How To Use the Python Map Function, and How To Use the Python Filter Function.