Python max() Built in Function
The max() function in Python returns the item with the highest value, or the item with the highest value in an iterable. An iterable can be a list, tuple, set, dictionary, string, etc. The max() function can also take two or more arguments and return the largest one.
Here are some examples of using max() function in Python:
Using max() with a single iterable
# This example returns the largest number in a list
numbers = [18 ,52 ,23 ,41 ,32]
largest = max(numbers)
print(largest)
# Output: 52
Using max() with multiple arguments
# This example returns the largest number among four arguments
result = max(5 ,10 ,25 ,99)
print(result)
# Output: 99
Using max() with strings
# This example returns the alphabetically last string in a list
words = ["apple" ,"banana" ,"cherry" ,"date"]
last = max(words)
print(last)
# Output: date
Using max() with a key function
# This example returns the longest string in a list using len() as a key function
words = ["hello" ,"world" ,"welcome" ,"to" ,"Python"]
longest = max(words ,key=len)
print(longest)
# Output: welcome
Using max() with dictionaries
# This example returns the key with the highest value in a dictionary
scores = {"Alice": 90 ,"Bob": 85 ,"Charlie": 95}
highest = max(scores ,key=scores.get)
print(highest)
# Output: Charlie
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment