Python max() Function Explained with Examples
Understand max() Syntax in Python
max (num1, num2, num3, ...)
|num1, num2, num3, …||The num value refers to the items to compare.|
The max(iterable) Syntax
Iterable refers to any item whose values can be looped over or if we try to understand in laymen’s term any item which is used at the right side of the for-loop.
max(iterable, *[, key, default])
|iterable||Iterable refers to the data collection, whose largest value is to be returned.|
|key||It is an optional value, and it takes iterable as an argument. It makes the comparison based on the value returned by this function.|
|default||This is an optional parameter, and It orders an object to return when it returns empty. If you don’t pass the default value, then it throws ValueError exception.|
Always the highest item of the iterable will be returned if we pass the iterable as a parameter. In case of multiple iterable declared as a parameter then the highest value of the list among other list items will be returned.
The max() Function Examples in Python
Find out how to get the highest numerical value among other numerical values using Python’s max() method.
x = max(9, 4, 6, 8, 7) print(x) # output = 9
x = max(5, 10, 25, 99) print(x) # output = 99
Get Largest Value from List using Python Max Function
In this example, we are going to get the largest value from the list using the max() method in Python 3. Find out in the given below code example how to to find out the maximum value in integer list or array.
numList = [30, 250, 140, 270, 60, 995, 200] print("The Max Value in collection : ", max(numList)) # output = 995
Python Max Method Example with String List
In this final example, we are going to define a string collection. Then, we will use the Max function to return the highest value from the collection. Here, you’ll see that Max method will use alphabetical order to find out the maximum value in a List.
superHeroes = ['Iron Man', 'Hulk', 'Groot', 'Black Widow'] print("The Max Value in collection : ", max(superHeroes)) # output = Iron Man
Find Largest Value in Nested List using Python Max Function
In this final example, we are going to create a nested list, then we’ll check out the flexibility of max method in Python. The max function will look into the first value in every nested list and get us a maximum value. Without further ado let’s begin, check out the example below:
NestedList = [[2, 3], [19, 11], [22, 55]] print("The Maximum Value : ", max(NestedList)) # output = [22, 55]