89DEVs

Python min() function

min() function overview

The min() function returns the smallest element. It can be used on an iterable or by passing one or multiple elements to it. And its opposite function is the max() function, which returns the largest element.

numbers and min()

The elements passed to the min() function can be numbers like integers, float values or complex numbers. The smallest of them is returned by min(). # min() function on numbers smallest = min(1, 3, 5, 4, 2.2, -5) print(smallest) The smallest number is returned by the min() function. -5

strings and min()

When used on strings, the min() function returns the lowest item in the alphabetical order. # min() function on strings result = min('aa', 'ab', 'ac') print(result) The lowest item in the alphabetical order is here 'aa'. aa

lists and min()

The min() function returns the smallest element in a list. For numbers the smallest number is returned and for strings the lowest item in alphabetical order is returned. # min() function on lists numbers = [5, 1, 3, 4, 2, -5] smallestNumber = min(numbers) print(smallestNumber) The smallest number in the list is -5. -5

min() and dictionaries

Applied on a dictionary, the min() function selects by default the smallest key. They key parameter can be used to also select the smallest value in the dictionary. # min() on dictionaries myDict = {1: 6, 2: 8, 3: 7, 4: 9} minKey = min(myDict) print(minKey) The smallest key is selected, the values are not considered on default. 1

syntax of min()

The syntax of the min() function is for iterables: min(iterable, [iterables, key, default]) And for non-iterables the syntax is: min(item1[, item2, item3, ... itemN])

arguments of min()

The min() function accepts either an iterable or one or more items as arguments.

return value of min()

The min() function returns either the smallest element from an iterable. Or the smallest item passed to it, if multiple items were passed.

                
        

Summary


Click to jump to section