Python Max Min Functions
What do max() and min() do?
max()
returns the largest item in an iterable or among two or more arguments.min()
returns the smallest item in an iterable or among two or more arguments.
Both can be customized with a key
function and a default
value.
Basic Syntax
max(iterable, *[, key, default])
min(iterable, *[, key, default])
max(arg1, arg2, *args[, key])
min(arg1, arg2, *args[, key])
iterable
: The sequence to search.key
: (Optional) Function to customize comparison.default
: (Optional) Value to return if the iterable is empty.
Examples with numbers, strings, lists
numbers = [3, 1, 4, 2]
print(max(numbers)) # Output: 4
print(min(numbers)) # Output: 1
words = ["apple", "banana", "cherry"]
print(max(words)) # Output: cherry (alphabetical order)
print(min(words)) # Output: apple
Using the key parameter
words = ["apple", "banana", "cherry"]
print(max(words, key=len)) # Output: banana
print(min(words, key=lambda w: w[-1])) # Output: banana (by last letter)
Using the default parameter
empty = []
print(max(empty, default=0)) # Output: 0
Summary
max()
andmin()
find the largest/smallest item in an iterable or among arguments.- Use
key
for custom comparison anddefault
for empty iterables. - Work with numbers, strings, and more.