Ultimate Guide to the Python min() Function
ADVERTISEMENT
Table of Contents
- Introduction
- Overview of the Python min() Function
- Passing one argument
- A file object
- Passing multiple arguments
- Strings
- Using the optional
key
parameter - Using the optional
default
parameter - How can I...?
- Get all minimum items
- Sort-Stability Preservation
- Conclusion
Introduction
The Python standard library contains several functions that are essential enough to be included in every installation of the language. One of those functions is min()
, which has been included as a built-in function since the initial release of Python 0.9.0 back in February 1991.
Through the years, min() has retained much of its original functionality, with a few updates here and there (the latest version 3.4.0). In this article, you'll get a detailed look at how the Python min() function works, what objects you can pass to it, and what values you can expect it to return.
Overview of the Python min() Function
Min()
is a function that takes an input and returns the item with the smallest value. For instance, min() will return the smallest number in a list of numbers:
>>> numbers = [1, 2, 3, 4, 5]
>>> min(numbers)
1
The code block above defines a list, numbers
, and passes it as an argument to min(), which returns the smallest number in the list.
Min() will also perform element-wise comparison across multiple objects and return the object containing the first smallest element that it encounters:
>>> smallnumbers = [1, 2, 3, 4, 5, 6, 7, 8]
>>> largenumbers = [85, 86, 87, 88, 89]
>>> min(smallnumbers, largenumbers)
[1, 2, 3, 4, 5, 6, 7, 8]
Here, min() compares the two lists, smallnumbers
and largenumbers
. The first elements are 1 and 85. The Python min() function will see that 1 < 85
and return the list with the smaller number. Notice that order matters here. If we prepend the value 90 to the smallnumbers
list, min() returns a different result:
>>> smallnumbers = [90, 1, 2, 3, 4, 5, 6, 7, 8]
>>> largenumbers = [85, 86, 87, 88, 89]
>>> min(smallnumbers, largenumbers)
[85, 86, 87, 88, 89]
Now, min() encounters the values 90 and 85 first. The comparison 90 > 85
tells min() that the list with the value 85 should be returned as the object with the minimum value. This behavior of element-wise comparison is key to understanding how the Python min() function works, and you’ll see it in-depth later on in this article.
These code examples represent the two basic forms of the Python min() function: passing one argument (the single list numbers
) and passing multiple arguments (the two lists smallnumbers
and largenumbers
). In the next two sections, you'll look at each of these forms in turn.
Passing one argument
The first syntax form that min() expects allows you to specify one positional argument:
min(iterable, [key=func, default=obj])
Let's take a closer look at each of the parameters:
iterable
(required): An iterable object (i.e. list, string, file).key
(optional): An ordering function used to sort the iterable.default
(optional): A value to return if the iterable is empty.
The first parameter is required: an iterable object. If you only pass one object to min(), then it must be an iterable object. The second and third parameters will be explained in more detail a bit later on. For now, let's take a closer look at the different iterable objects that you can pass to the Python min() function.
A string
When you pass a string as an object to min(), the function will iterate through every item in the string and return the element with the lowest value:
>>> min("hello")
'e'
Here, the string "hello"
is passed as an argument to min(), which returns the letter 'e'
. If you know your letters, then you know that 'e' comes before 'h', 'l', and 'o' in the alphabet.
However, there are some instances where the Python min() function might return a value from a string that you don't expect:
>>> min("Abigail!")
'!'
What's going on here? There's no exclamation point in the alphabet. So how is this the minimum value?
To understand what values min() will return from a string, you need to understand how Python sorts characters in general. By default, the Python min() function uses ASCII sort order to sort strings. If you examine the ASCII table, then you'll see that special characters like exclamation marks ('!'
) and dollar signs ('$'
) come before alphabet characters.
It's also important to note that uppercase letters ('ABC'
) come before lowercase ones ('abc'
) in the ASCII table. As a result, the Python min() function by default will always return uppercase values as the minimum element in a string containing both uppercase and lowercase letters:
>>> min("Abigail")
'A'
Here, when the special character '!'
is removed from the string 'Abigail!'
, min() returns the next value that comes earliest in the ASCII table, which is 'A'
.
A container
In the overview section, you saw how min() returned the smallest value in a list of numbers. This functionality works on other types of containers, as well:
>>> num_tup = (1, 2, 3, 4, 5) # A tuple
>>> min(num_tup)
1
>>>
>>> num_set = {0, 2, 4, 6, 8} # A set
>>> min(num_set)
0
>>>
>>> sweets = {'ice cream': 10, 'donuts': 9, 'candy': 6, 'cookies': 2}
>>> min(sweets)
'candy'
Here, you can see how the Python min() function works with various built-in containers. Min() has no trouble finding and returning the smallest value in a tuple or a set of numbers.
Note that min() doesn't return a number from the dictionary sweets
. When a dictionary is passed as an argument, min() will first sort the dictionary by key from smallest to largest. Then, it will return the smallest key in the dictionary, instead of the smallest value. This is why the return value from min(sweets)
is 'candy'
, even though the key with the smallest value is 'cookies'
.
If instead you'd like to return the smallest value in the dictionary, then simply pass the dictionary's .values()
as a parameter to min():
>>> min(sweets.values())
2
This returns 2 as expected.
A file object
By now, you know well that min() will take any iterable object as an object and return the item with the smallest value. This is the case for objects that you introduce from outside the Python environment itself - a file on your system, for instance.
In the directory where you're running the Python interpreter, create a file lines.txt
with the following text:
This is the first line.
This is the second line.
This is the third line.
Now, we've reached the end. Finally!
Then, in the Python interpreter, open the file in read-only mode and pass it as an argument to min():
>>> file = open('lines.txt', 'r')
>>> min(file)
"Now, we've reached the end. Finally!\n"
The output shows that the line starting with the "smallest" value in the file is actually the last one. This is because the line starts with the uppercase letter 'N'
, which comes before uppercase 'T'
in the ASCII table.
NOTE: The Python min() function in this example is comparing the first element in each line, and returning the first line whose element has the smallest value. This is an example of element-wise comparison, which you'll dive deeper into in the section on passing multiple arguments.
Let's consider one more example. Create another file numbers.txt
in the same directory with a few random numbers, one on each line. For example:
46
61
684
648
18
189
648319
78
96416
You should expect min() to return the line that has the number 18 on it, and that's exactly what it does:
>>> file = open('numbers.txt', 'r')
>>> min(file)
'18\n'
Though the numbers in each line are read in as strings, min() is still able to return the correct value.
An integer
Just for curiosity's sake, what happens if you pass a single integer as an argument to min()? Let's take a look:
>>> min(12)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
Unsurprisingly, min() raises a TypeError
, because integers aren't iterable, of course. But what happens if you pass two integers? This, as you'll see in the next section, is allowed:
>>> min(11, 12)
11
As long as more than one is passed, integers are a perfectly valid data type that you can pass to the Python min() function.
Passing multiple arguments
The second syntax form that min() expects allows you to pass multiple arguments:
min(arg1, arg2, *args[, key=func])
Let's take a closer look at each of the parameters:
arg1
(required): The first object to compare.arg2
(required): The second object to compare.*args
(optional): Any additional objects to compare.key
(optional): An ordering function used to sort the items.
Here, the first two arguments are required: if the objects you're passing aren't iterable, then you need to specify at least two of them in order for min() to have something to compare. However, the *args
parameter allows you to pass an unspecified number of arguments - in other words, as many as you want - to min().
When passing multiple arguments, the Python min() function often uses element-wise comparison to sort values. This means that it will take the first element in each object and compare those; if one is smaller than the other, then min() will return the object whose first element is the smallest. If the two elements are the same, however, then min() will proceed to the second element in each object and compare those. It repeats this process until one object is determined to have an element that's smaller than the other. If the objects are the same, then min() will return the first object passed in.
Let's take another look at the different objects you can pass to the Python min() function and what return values you can expect.
Strings
You've already seen how min() iterates through a single string. When you pass in two or more strings, then min() will use element-wise comparison to determine which string contains a smaller value:
>>> min('Bob', 'Boc') # letter-by-letter comparison
'Bob'
These two strings are the same in every regard except for the final letter. Min() starts at the first element, 'B'
, which is the same in both strings, and proceeds to the second element, 'o'
, which is also the same in both strings. Finally, min() compares the final elements, which are 'b'
and 'c'
, respectively. Based on ASCII sort order (and common sense), 'b'
comes before 'c'
, so the string 'Bob'
is returned as the minimum value.
To prove that the Python min() function handles strings element-by-element, consider the following scenario:
>>> min('Bob', 'XAA')
'Bob'
This line of code also returns 'Bob'
as the minimum object. Note that the second string 'XAA'
contains the uppercase 'A'
character, which comes before any of the other characters in the ASCII table. However, because the first character of that string is an 'X'
, min() never proceeds to consider the remaining characters. It simply compares the first two elements, 'B'
and 'X'
, determines that 'B'
comes before 'X'
, and returns the strings 'Bob'
. This behavior is to be expected, as humans use this same method to alphabetize lists of names.
The ASCII sort order is preserved when passing multiple strings to min():
>>> min('Bob', 'bob') # Uppercase letters are ‘smaller’ than lowercase ones
'Bob'
>>>
>>> min('Bob', '!$^)(') # Special characters are ‘smaller’ than alphanumeric ones
'!$^)('
>>>
>>> min('A', '1') # Numbers are ‘smaller’ than letters
'1'
It may be helpful to keep a copy of the ASCII Table nearby to ensure you know which value to expect from min().
Containers
Min() uses element-wise comparison on lists as well. For example:
>>> min([1, 4, 3], [1, 3, 5])
[1, 3, 5]
Here, min() returns the second list [1, 3, 5]
as the minimum, even though the first list has smaller numbers overall. Again, min() considers the first element across both lists, sees that they are the same (1), and proceeds to the next element. The second elements are 4 and 3. Since 3 < 4
, min() simply designates the list with the element 3 as the minimum. It never proceeds to compare 3 and 5.
Here's a more extreme example:
>>> min([2, 0, 0], [1, 99, 999])
[1, 99, 999]
The values in the second list are much larger overall than the ones in the first. However, 1 < 2
, so min() compares the first element across both lists and stops its comparison there, returning [1, 99, 999]
as the minimum value.
Tuples work in a similar manner:
>>> min((1, 9, 2), (1, 3, 5)) # Comparing two tuples
(1, 3, 5)
This command compares two tuples and returns (1, 3, 5)
as the minimum object.
Sets are a bit trickier. Calling min() on two or more sets may not return quite the result you’d expect:
>>> min({1, 2, 3, 4}, {0, 1, 2})
{1, 2, 3, 4}
The second set {0, 1, 2}
is both shorter in length and has a smaller overall value of 0. However, the first set is returned instead. The section on Sort-Stability Preservation will explain more about why this is.
For now, let's take a look at how to compare two dictionaries:
>>> sweets = {'ice cream': 10, 'donuts': 9, 'candy': 6, 'cookies': 2}
>>> flavors = {'vanilla': 10, 'chocolate': 8, 'banana': 3, 'strawberry': 6}
>>> min(sweets, flavors)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'dict' and 'dict'
Unfortunately, this doesn't work out quite as well. dict
objects in Python are not comparable to one another, so min() has no way to know how to compare the two objects.
Still, there are other hacks you can do to get the Python min() function to work with dictionaries. These include comparing the keys or the values of each:
>>> min(sweets.keys(), flavors.keys())
dict_keys(['ice cream', 'donuts', 'candy', 'cookies'])
>>>
>>> min(list(sweets.values()), list(flavors.values()))
[10, 8, 3, 6]
min() will easily determine which dictionary has the smaller keys, and which has the smaller values. Again, these objects are compared element-wise, and the minimum result will be the one where a minimum value is first found.
File Objects
Earlier, you saw how the Python min() function will iterate through a file object and return the line with the minimum value. Min() will also work with multiple file objects, returning whatever value you specify as an argument.
For example, say you're interested using min() to get the size of the smallest file in a directory. In this example, the current working directory contains three files of different sizes: 'five-kilobytes'
, 'eleven-kilobytes'
, and 'thirty-two-kilobytes'
. You can use the os
module to read in those file objects and pass them in as arguments to min():
>>> import os
>>> os.listdir('.') # List all files in the current directory
['eleven-kilobytes', 'thirty-two-kilobytes', 'five-kilobytes']
>>> min([os.path.getsize(f) for f in os.listdir('.')])
5120
This code block uses a list comprehension to get the size of all files in the current working directory. The result is then passed as an argument to min(), which returns the size of the smallest file.
Using the optional key
parameter
You've seen several examples of how to use the Python min() function to return the smallest value in an iterable or the smallest of several objects. However, the functionality may seem a bit limited at this point. For example, you haven't been able to compare objects of different data types, and min() won't necessarily return the iterable with the smallest value in it, just the first minimum value it encounters.
Fortunately, the optional key
parameter allows you to mitigate both of these concerns.
Comparing objects of different types
The key
parameter allows you to specify a function to apply to the objects you pass to min() before sorting begins. These include str()
, int()
, and list()
, for instance. Consider the following traceback errors:
>>> min(1, "a", 3, "2", 0.5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'str' and 'int'
>>>
>>> min((1, 2, 3), [1, 2, 4])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'list' and 'tuple'
In the first example, you're trying to find the minimum value of several objects, but their data types differ. This raises a TypeError
, unless you use the key
parameter to convert them to the same type:
>>> min(1, "a", 3, "2", 0.5, key=str)
0.5
>>> min((1, 2, 3), [1, 2, 4], key=tuple)
(1, 2, 3)
key=str
says that all the elements should be treated as strings, and key=tuple
says they should all be treated as tuples. Now, the Python min() function has no trouble comparing these elements, as they've all been converted to the same type.
Sorting by a different method
The Python min() function uses default sort methods to find the object with the minimum value. This results in return values like the following:
>>> min([1, 4, 2], [1, 3, 5, 7])
[1, 3, 5, 7]
The second list [1, 3, 5]
is returned as the minimum value, despite the fact that the first list [1, 4, 2]
contains the smallest value overall (2). Moreover, the sum of the first list is smaller than the second, and the length of it is smaller as well.
You can use key
to specify what method you want to use to find the minimum value:
>>> min([1, 4, 2], [1, 3, 5, 7], key=min) # Return the minimum overall value
[1, 4, 2]
>>>
>>> min([1, 4, 2], [1, 3, 5, 7], key=len) # Return the minimum length
[1, 4, 2]
>>>
>>> min([1, 4, 2], [1, 3, 5, 7], key=sum) # Return the minimum sum
[1, 4, 2]
The first call to min() specifies key=min
, which compares the minimum value in each list. Now, the list with 2 in it is returned as the minimum. The second call to min() specifies key=len
, which returns the object with the shortest length; again, this is the first list, with only 3 elements. Lastly, the final call to min() specifies key=sum
, which says to return the object with the smallest sum overall. The first list has a sum of 7, while the second has a sum of 16. In all three cases, you're able to override the default sort functionality by specifying a different key
.
This works on strings as well:
>>> min("abigail", "Billy")
'Billy'
>>>
>>> min("abigail", "Billy", key=str.lower)
'abigail'
ASCII sort order says that 'B'
comes before 'a'
, so 'Billy'
is returned as the minimum value unless a different key
is specified. Here, key=str.lower
changes all strings to lowercase before comparison, resulting in the minimum value 'abigail'
.
You can also define your own functions and pass them in as the key
. Let's wrap the previous example in a function called lowercase()
:
>>> def mylowercase(x):
... return x.lower()
...
>>> min("abigail", "Billy", "bob", key=mylowercase)
'abigail'
It's the same result as before. The only difference is that the key
is a function you defined, instead of a built-in function that Python provides.
Lastly, you can use lambda functions (anonymous functions) to change the sort function:
>>> users = [(130, 'Abigail'), (315, 'Billy'), (98, 'Jack'), (16, 'Will')]
>>> min(users)
(16, 'Will')
>>>
>>> min(users, key=lambda x: x[1])
(130, 'Abigail')
You define a list users
with several tuples in the form (userid, username)
. Calling min() on this tuple directly will sort the list by the index 0
element in each tuple, which returns (16, 'Will')
as the smallest object.
You change this functionality by passing key=lambda x: x[1]
which says to instead sort by the index 1
element of x
, which is just another reference to the users
list. Now, min() uses the second element of each tuple as a basis for comparison, returning (130, 'Abigail')
, whose string is the minimum value out of all of the tuples.
Using the optional default
parameter
There's one last optional parameter that you can pass to the Python min() function, and that's default
. Consider the following traceback error:
>>> min([])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: min() arg is an empty sequence
If you pass an empty iterable as an argument to min(), it will raise a ValueError
. Arguments to min() cannot be empty. Unfortunately, sometimes you might want an iterable to start out empty; for instance, if you're declaring the variable at the top of a loop and haven't populated it yet.
To get around this, you can pass in a default
value that min() will revert to if there are no objects in the iterable to compare:
>>> min([], default=0)
0
Here, min() returns the default
value 0, even though the list is empty.
Be careful not to confuse empty objects with undefined arguments, or no arguments at all. The following lines of code will not execute:
>>> min(hello, default=0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'hello' is not defined
>>>
>>> min()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: min expected 1 argument, got 0
The first error is raised because hello
is an undefined variable. The second is raised because you're not passing anything to min(), which requires at least one argument. For curiosity's sake, let's rewrite the second example:
>>> min(, default=0)
File "<stdin>", line 1
min(, default=0)
^
SyntaxError: invalid syntax
That just doesn't look right, does it? min() will happily take empty elements, but it won't execute if there just isn't anything there. Again, the element can be empty, but not nonexistent.
How can I...?
In this last section, let's take a quick look at some of the ways to count and index minimum values using the Python min() function.
Ignore element-wise comparison
Earlier, you saw that min() will compare objects element-wise:
>>> min([1, 9, 2], [1, 3, 5])
[1, 3, 5]
What if you want to ignore this functionality? How can you find the smallest value overall?
By changing the way the items are sorted, you can work around the Python min() function's propensity for element-wise comparison to ensure you get the actual minimum value available in an object. Here are a few ideas, some of which you've seen before:
>>> min([1, 9, 2], [1, 3, 5], key=min) # Get the overall minimum value
[1, 9, 2]
>>>
>>> min([1, 9, 2], [1, 3, 5], key=set) # Create a set first
[1, 9, 2]
>>>
>>> min([1, 9, 2], [1, 3, 5], key=sorted) # Sort the list first
[1, 9, 2]
Note that while min() will still use element-wise comparison, these tricks ensure that the true minimum values are seen as soon as possible.
Get all minimum items
This is likely something you'll want to do when working with dictionaries, where multiple keys can have the same minimum value. Consider the following dictionary:
>>> fruits = {'apple': 5, 'orange': 5, 'banana': 7, 'grapefruit': 8}
>>> min(fruits)
'apple'
It's obvious that both 'apple'
and 'orange'
share the minimum value 5. However, min() only returns the first object it encounters. To get all the keys in a dictionary that have the minimum value, you can use a list comprehension:
>>> [fruit for fruit in fruits if fruits[fruit] == min(fruits.values())]
['apple', 'orange']
This says to return a key fruit
if its value fruits[fruit]
is equal to the minimum value min(fruits.values())
. Now, you get back both 'apple'
and 'orange'
as expected.
Count the number of minimum items
For lists, min() will only return the minimum value once, even if it occurs multiple times:
>>> numbers = [5, 2, 2, 6, 7, 2, 8, 9, 4, 2]
>>> min(numbers)
2
To figure out how many elements have the minimum value, you can simply use .count()
:
>>> numbers.count(min(numbers))
4
This returns the number of items in numbers
that have the value 2.
Find the index of minimum items
Finally, knowing what the minimum value is might not be useful enough for you. Chances are you'll want to know where in a list, for instance, that minimum value occurs.
You can use .index()
to locate the index of an element in a list. Passing min(numbers)
as an argument will give you the location of the element with the minimum value:
>>> numbers = [5, 2, 2, 6, 7, 2, 8, 9, 4, 2]
>>> numbers.index(min(numbers)) # Returns first match
1
The above code block shows that the list numbers
has a minimum value of 2, which first occurs at index 1
.
However, recall that there are three other elements in the list that also have the minimum value. numbers.index(min(numbers))
only returned the first one. How can you get the rest of them?
As always, list comprehensions are a handy solution:
>>> [i for i, j in enumerate(numbers) if j == min(numbers)]
[1, 2, 5, 9]
>>>
>>> numbers[1], numbers[2], numbers[5], numbers[9]
(2, 2, 2, 2)
The enumerate()
function will loop through an iterable and grab the index i
and value j
of each element. This list comprehension says to spit out the index i
of each element if its value j
is equal to min(numbers)
. It returns the indices [1, 2, 5, 9]
, which we can pull out of numbers
to confirm that the minimum value is indeed found at each of these locations.
Sort-Stability Preservation
Sets can show some unique behavior when passed into min(). Take the following code block, for instance:
>>> min({1, 2, 3, 4}, {0, 1, 2})
{1, 2, 3, 4}
The two sets {1, 2, 3, 4}
and {0, 1, 2}
are passed as arguments to min(). The second set contains the smallest overall value 0 and is the shortest in length, with only 3 elements. However, min() returns the larger (both in length and overall value) set as the minimum. What gives?
Well, in Python, sets are unordered collections of unique values, and comparison between them is relational. As a result, min() can’t use element-wise comparison to determine which set should be the minimum. Instead, the comparison operator <
tries to see if one set is a subset of another:
>>> {0, 1, 2} < {1, 2, 3, 4} # {0, 1, 2} is not in {1, 2, 3, 4}
False
>>>
>>> {1, 2, 3} < {1, 2, 3, 4} # {1, 2, 3} is in {1, 2, 3, 4}
True
It's necessary to keep this behavior in mind when passing multiple sets to the Python min() function for comparison. That's because when you pass in sets where one is not a subset of another, min() will fail to return the set with the minimum value. Instead, it will simply return the first object it encounters:
>>> min({1, 2, 3, 4}, {0, 1, 2})
{1, 2, 3, 4}
>>>
>>> min({0, 1, 2}, {1, 2, 3, 4})
{0, 1, 2}
In the code block above, the same two sets are passed as arguments to min(), and each set is returned as the minimum value. The comparisons {1, 2, 3, 4} < {0, 1, 2}
and {0, 1, 2} < {1, 2, 3, 4}
both return False
since neither set is a subset of the other. The Python min() function, unable to make a determination on which set is the minimum, simply returns the first object it encountered.
This can be further proven by passing in various sets of different shapes with different values and observing the behavior of min() as the order of the arguments are switched:
>>> min(a, b)
{99, 71, 42, 12, 15, 80, 83, 52, 53, 60} # a chosen as the minimum
>>>
>>> min(b, a)
{3, 70, 77, 46, 50, 86, 23, 57, 60, 30} # b chosen as the minimum
>>>
>>> min({1, 9, 2}, {1, 3, 5}) # {1, 9, 2} chosen as the minimum
{1, 2, 9}
>>>
>>> min({1, 3, 5}, {1, 9, 2}) # {1, 3, 5} chosen as the minimum
{1, 3, 5}
This is an example of sort-stability preservation. In other words, if min() can’t determine whether one item is more minimal than the other, then it will retain the order of the items as passed in and return the first object it encounters.
To confirm this, take a look at the following code block:
>>> min({1}, {2, 3}, {4, 5, 6})
{1}
>>>
>>> min({2, 3}, {4, 5, 6}, {1})
{2, 3}
>>>
>>> min({4, 5, 6}, {1}, {2, 3})
{4, 5, 6}
You pass in three sets to the Python min() function, switching their lengths as well as the order in which they are passed in. Each time, min() returns the first set as the minimum, regardless of how many elements are in it or what the overall minimum value of the set is.
You can nudge min() in the right direction by using the key
argument to explicitly say that you want it to take the minimum value of each set into account:
>>> min({1}, {2, 3}, {4, 5, 6}, key=min)
{1}
>>> min({2, 3}, {4, 5, 6}, {1}, key=min)
{1}
>>> min({4, 5, 6}, {1}, {2, 3}, key=min)
{1}
This correctly returns the set with the minimum overall value each time.
Let’s return to the first example from this section. Even though neither set is a subset of the other, you can get min() to return the "correct" value each time by explicitly passing the key
parameter:
>>> min({1, 2, 3, 4}, {0, 1, 2}, key=min)
{0, 1, 2}
>>>
>>> min({0, 1, 2}, {1, 2, 3, 4}, key=min)
{0, 1, 2}
>>>
Now, instead of looking for subsets, min() instead compares the minimum elements of each set and uses this result to return the expected value.
Sort-stability preservation can also be seen when comparing strings that are mostly similar. In this manner, min() will take into account multiple criteria - such as ASCII sort order and length - when comparing strings. For example:
>>> min("Cheese", "Cheesey")
'Cheese'
The two strings "Cheese"
and "Cheesey"
are completely similar except for an extra 'y'
in the second string. ASCII sort order has both strings equal to each other up until the sixth element. After this, the first string has no seventh element to compare the second string to. Intuitively, at this point the Python min() function would switch from ASCII sort order to string length as a comparison method. It would automatically determine that "Cheese"
has length 6 and "Cheesey"
has length 7. Finally, it returns "Cheese"
as the string with the minimum value, since its length is shorter than the alternative.
Conclusion
In this article, we took a deep dive into the Python min() function to understand what parameters it takes, what data types it operates on, and what values it returns.
You've seen how to specify the sort function, compare objects of different types, and pass default parameters for empty iterables. You've also how to count and index minimum values and use your own functions to decide how objects should be compared.
The Python min() function is part of the Python standard library, and is likely one of those functions you'll come across early in your Python learning journey. If you're interested in learning more about the basics of coding and software development, check out our Coding Essentials Guidebook for Developers, where we cover the essential languages, concepts, and tools that you'll need to become a professional developer.
Thanks and happy coding! We hope you enjoyed this article! If you have any questions or comments, feel free to reach out to jacob@initialcommit.io.
Final Notes
Recommended product: Coding Essentials Guidebook for Developers