Friday, January 24, 2025
HomeProgrammingPython - max() function

Python – max() function

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).
See also  What is OSPF Protocol (Open Shortest Path First Protocol)?

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

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x