How to use the Python Max function?In this short tutorial, we look at the different ways the Python Max function can be used. We also have a section where look at the code for each section to help facilitate further understanding.
Table of Contents
- Where can the Python Max function be used?
- Using Max on Iterables
- Limitation and Caveats
- Other Related Concepts
Where can the Python Max function be used?As the name suggests the Max function in python is used to return the largest (Maximum) element. Although the value returned is always the largest the methods it uses to arrive at it is based on the arguments passed as a parameter. And depending on the parameter, there are two syntaxes.
The first is quite straightforward, we use this when we are looking to pass a few values and looking to find the maximum among them.
Parameter:arg1, arg2 are values that you are looking to compare, could be a number or a string. .
We shall look at the other syntax, while looking at iterables.
Using Max on IterablesIn this sections we look at how the Python Max function works with iterables. When iterables are passed as a parameter, the max function returns the largest value in the iterable. And the syntax is as follows.
Paramater:Iterables - Commonly used ones are - lists, dictionaries, tuples, strings. Default - This value is returned in case the iterable is empty
While using the python max function on a dictionary, the largest key is returned.
While using the python max function on a list of strings the strings are ordered alphabetically and the largest string is returned.
Limitations and Caveats
- In case an empty iterables is passed as a parameter, ValueError is returned. However, if a default value exists then that is passed.
- Passing values of different data types returns a TypeError