The max()
function in Python is used to return the largest item from an iterable (like a list, tuple, or string) or the largest of two or more arguments.
Syntax:
max(iterable, *, key=None, default=None)
- iterable: An iterable (e.g., a list or tuple) from which the largest item will be returned.
- key (optional): A function that takes one argument and returns a value to use for sorting/comparing the items in the iterable.
- default (optional): A default value to return if the iterable is empty (useful when not passing
key
).
Alternatively, max()
can be used with multiple arguments:
max(arg1, arg2, *args, key=None)
Examples:
1. Finding the largest number in a list:
numbers = [1, 3, 5, 7, 2]
largest = max(numbers)
print(largest) # Output: 7
2. Using key
argument:
words = ['apple', 'banana', 'cherry']
longest_word = max(words, key=len)
print(longest_word) # Output: 'banana'
3. With default value when iterable is empty:
empty_list = []
result = max(empty_list, default='No data')
print(result) # Output: 'No data'
4. Using max()
with multiple arguments:
a = 10
b = 20
c = 15
result = max(a, b, c)
print(result) # Output: 20