The max()
function returns the highest value from a list, tuple, set, or any iterable. It’s useful for finding the largest number, longest string, or highest-scoring item in a dataset.
Example
numbers = [10, 25, 7, 99, 42]
print(max(numbers))
# Output: 99
This finds the largest number in the list.
Syntax
max(iterable, key=None)
max(arg1, arg2, ..., key=None)
- iterable → A list, tuple, set, or other sequence to find the max value from.
- arg1, arg2, … → Multiple values can be compared directly.
- key (optional) → A function to customize comparisons.
- Returns → The highest value.
1. Finding the Maximum of Multiple Numbers
print(max(10, 20, 30))
# Output: 30
Works without needing a list.
2. Finding the Longest String
words = ["apple", "banana", "cherry"]
longest = max(words, key=len)
print(longest)
# Output: banana
key=len
finds the string with the most characters.
3. Finding the Maximum in a Dictionary
Find the highest dictionary value.
scores = {"Alice": 85, "Bob": 92, "Charlie": 78}
top_scorer = max(scores, key=scores.get)
print(top_scorer)
# Output: Bob
Returns the key with the highest value.