Remember
min() returns the smallest item according to comparison or a supplied key.
min() returns the smallest item according to comparison or a supplied key.
Follow the example, change its sample, and compare what happens.
Explain the result and test your understanding.
Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.
Follow the code and watch its state change. Guided simulation.
numbers = [3, 2, 5]
print(min(numbers))Top-level scope
[3, 2, 5]min() returns the smallest item according to comparison or a supplied key.
(no output)
What do you expect this program to print?
EXAMPLE INSTRUCTIONS
numbers = [3, 2, 5]
print(min(numbers))
|
v
DISPLAYED RESULT
2
FINAL BINDINGS
numbers --> object 1 (list)
object 1: [3, 2, 5]Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.
Choose a sample and follow its execution. Guided simulation.
numbers = [3, 2, 5]
print(min(numbers))Top-level scope
[3, 2, 5]The example has finished. Compare the final output with the values and references above.
2
What do you expect this program to print?
numbers = [3, 2, 5]
print(min(numbers))min() FunctionThe min() function in Python returns the smallest item from a list, tuple, or multiple values passed to it. It is one of the most useful built-in functions for comparing and analyzing data.
min(iterable, *[, key, default])
min(arg1, arg2, *args[, key])
iterable: A sequence (like list, tuple, set, etc.) of comparable items.arg1, arg2, *args: Two or more values for direct comparison.key (optional): A function to customize the comparison logic.default (optional): Value to return if the iterable is empty (used only with default keyword).numbers = [10, 5, 22, 3, 19]
print(min(numbers))
3
print(min(4, 1, 7, -2, 9))
-2
words = ["banana", "apple", "cherry"]
print(min(words))
apple
Note: Strings are compared lexicographically (alphabetical order).
Find the shortest word based on length:
words = ["elephant", "cat", "hippopotamus"]
shortest = min(words, key=len)
print(shortest)
cat
empty = []
result = min(empty, default=0)
print(result)
0
min([]) without a default will raise a ValueError.TypeError.min() is frequently used in problems involving optimization, such as finding the minimum distance, cost, or value in arrays.
min() returns the smallest item from a sequence or argumentskey for custom comparisondefault to avoid errors with empty iterablesWrite a program that reads five numbers from the user and prints the smallest one.
nums = [int(input("Enter a number: ")) for _ in range(5)]
print("Smallest number is:", min(nums))
Connect what you noticed in the example with the idea below.
min() returns the smallest item according to comparison or a supplied key.
min() always returns the first item of the iterable.
This is the misconception to avoid.Reference checks are optional and do not count toward course progress.