In Python, one of the inbuilt functions is the max function. This function is used to return the item with the highest value, or the item with the maximum value if parameters are provided. In this tutorial, we will focus on defining and using the max function in Python.
Step 1: Basic Usage of Max
The max function can be used with iterable (list, tuple, etc), as well as with two or more parameters.
Here is an example:
1 2 |
numbers = [1, 3, 2, 8, 5, 10] print(max(numbers)) |
Step 2: Max with Different Data Types
The max function is versatile and it can handle many different types of data such as strings and dictionaries, not just numbers. However, when comparing different data types, the function may not work as intended.
1 2 |
words = ["apple", "banana", "cherry"] print(max(words)) |
Step 3: Max with a Key Parameter
If you would like to compute the maximum value based on a specific rule or function, you can use the key parameter in the max function. The function specified by key will be used to order the elements and select the maximum.
1 2 |
words = ["apple", "banana", "cherry"] print(max(words, key=len)) |
Displaying the full code:
1 2 3 4 5 6 7 8 9 10 |
#max with numbers numbers = [1, 3, 2, 8, 5, 10] print("Max in numbers:",max(numbers)) #max with different data types words = ["apple", "banana", "cherry"] print("Max in words:", max(words)) #max with key parameter print("Largest word:", max(words, key=len)) |
Output:
Max in numbers: 10 Max in words: cherry Largest word: banana
Conclusion
In conclusion, the max function in Python is a very useful built-in function to find the maximum value among data elements. By offering the flexibility of searching different types of data and applying different rules through the key parameter, max can be used to perform a wide variety of maximum value searches in Python.