How to Use the min() Function in Python
In this tutorial, you will learn how to find the smallest value in Python using the min() function. This tutorial also provides an example of finding the smallest value in a list without using the built-in functions min() and sort().
Python min() Function Syntax
The syntax of the min() function is as follows:
min(list)
Or:
min(arg1, arg2, *args)
Examples:
min([100, 200, 300, 400]) min(10, 20, 40, 30)
Remark
- List: the list containing the values for which you want to find the minimum value.
Examples
Using min() to find the smallest value in a group of numbers
The following code shows an example of finding the smallest of three numbers:
# find the smallest of 3 numbers min_value = min(200, 170, 125) print("The smallest value: ", min_value)
Output:
The smallest value: 125
The following code shows an example of finding the smallest of four numbers:
# find smallest of 4 numbers min_value = min(40, 80, 125, 90) print("The smallest value: ", min_value)
Output:
The smallest value: 40
Finding the smallest value in the list
The following program finds the smallest value in a list of numbers:
# find the smallest value in a list numbers = [110, 220, 300, 90, 230, 140, 440, 130, 170] smallest_value = min(numbers) print("The smallest value: ", smallest_value)
Output:
The smallest value: 90
Finding the smallest number without min()
The following program uses a FOR loop and IF statement to find the smallest number in a list:
# find the smallest value in a list numbers = [1200, 1280, 1100, 920, 320, 1240] min = numbers[0] for number in numbers: if number < min: min = number print("The smallest number: ", min)
Output:
The smallest number: 320
The following program uses a FOR loop and an IF statement to find the second-smallest number in the list:
# find the second smallest number in a list numbers = [1200, 1280, 1100, 920, 320, 1240] length = len(numbers) for i in range(length): for j in range(i + 1, length): if numbers[i] > numbers[j]: num1 = numbers[i] num2 = numbers[j] numbers[i] = num2 numbers[j] = num1 second_smallest = numbers[1] print("The second smallest number: ", second_smallest)
Output:
The second smallest number: 920
The following program uses a FOR loop and an IF statement to find the third smallest number in the list:
# find the third smallest number in a list numbers = [1200, 1280, 1100, 920, 320, 1240] length = len(numbers) for i in range(length): for j in range(i + 1, length): if numbers[i] > numbers[j]: num1 = numbers[i] num2 = numbers[j] numbers[i] = num2 numbers[j] = num1 third_smallest = numbers[2] print("The third smallest number: ", third_smallest)
Output:
The third smallest number: 1100
Read more:
Summary
In this tutorial, you learned how to find the smallest value in a list of numbers with/without the built-in function min().