The main reason python is considered one of the easiest to learn and user-friendly languages because it offers different types of built-in functions that are super useful. One such function is the python max function. If you already use it in your program, you would know how many times it has made our life easy.Â
Python max function is an inbuilt global function that is used to fetch the maximum value from a list, tuple, or dictionary. Sometimes, we need to fetch the highest values from the list and have a check on them. With the help of max(), we can do it easily without creating a new function.
Let’s understand how this works and some interesting use cases. Before that, let’s have a look at how it works.
Usage of Python Max Function
When we want to find the largest element among the given elements or list of items, or maybe we want to find the list among many lists that contain the highest item, even we can find the string starting with the highest value alphabetically.
Syntax-
- max(iterable, *[, default=obj, key=func]) -> value
Here, iterable refers to object like list,string,tuple,etc.
default= If we pass an iterable without any values in the max function it will result in the following error-
max() arg is an empty sequence
So, we can pass a default parameter with any value we want. For example-
print(max([],default="No value"))
Output:
No value
key= We will understand this parameter with an example.
list1=["a","b","c","Z"]
print(max(list1))
Output:
c
In the example above, alphabetically ‘Z’ is the largest value, but as the ASCII value of ‘Z’ is lesser than that of ‘c’, we have got the output as ‘c’. To solve this problem, we will make every value in the same form using the key parameter. Let’s see how-
list1=["a","b","c","Z"]
print (max(list1, key=str.lower))
Output:
Z
- max (arg1, arg2, *args, *[, key=func]) -> value
When we do not need to pass the iterable and just the value in the arguments, we use this syntax.
print(max(1,2,3,4,5,6))
Output:
6
There is no default parameter and the key parameter is same as above.
Examples of Python Max FunctionÂ
- Finding the highest value in a dictionary-
dict1 = {'a':5,'b':1,'c':9,'d':2}
print(max (dict1.values()))
Output:
9
- We are finding the largest value in the string.
print(max("ashwini"))
Output:
w
- Find the largest key in the dictionary
Dict1={1:’c’,2:’b’,3:’a’}
print(max(Dict1))
Output:
3
- If we want to find the string with maximum length-
print(max("ashwini","mandani","max","function",key=len))
Output:
function
- Suppose we want to find the list that has the highest element in it
list1=[1,2,3]
list2=[3,4,5]
list3=[5,6,1]
print(max(list1,list2,list3))
Output:
[5,6,1]
- Similarly, if we want to find the list with most number of elements –
list1=[1,2,3,5]
list2=[3,4,5]
list3=[5,6,1]
print(max(list1, list2, list3, key=len))
Output:
[1, 2, 3, 5]
- We can also apply max function on a pandas Series named series.
print(series)
0 643.09 1 656.22 2 487.29 3 1504.75 4 1275.46 Name: size, dtype: float64
print(max(series))
Output:
1504.75
Now that we have learned how to use python max function with various data types. Let us implement our own max function.
Implementing our own python max function-
Without Recursion
def max(list1):
for i in range(0,len(list1)-1):
for j in range(0,len(list1)-i-1):
if list1[j] > list1[j+1]:
list1[j],list1[j+1]=list1[j+1],list1[j]
return list1[-1]
list1=[7, 5, 9, 6, 3]
print(max(list1))
Output:
9
With Recursion-
Let’s look at how we can create our own max function with recursion. We can only pass a single list with multiple elements.
def recursive_max(list1):
if list1[1:]:
if list1[0] > rec_max(list1[1:]):
return list1[0]
else:
return rec_max(list1[1:])
elif not list1:
return
else:
return list1[0]
list1 = [12, 56, 23, 80]
print(recursive_max(list1))
Output:
80
list1 = ['a','b','c','d']
print(recursive_max(list1))
Output:
d
Some Common Errors while using Python Max FunctionÂ
TypeError– This is a very common error we face. This error generally occurs when in the max function we pass incompatible data types with each other like string and integer or float and string.
For example-
print(max("ashwin",1))
Output:
TypeError- '>' not supported between instances of 'int' and 'str'
Also, if we don’t pass any value in the max function, we get this error. For this we use default parameter.
The Complimentary method of python max function is min function, which is used to find the minimum value.Â
print(min([1,2,3,4,5]))
Output:
1
Must Read:
- How to Convert String to Lowercase in
- How to Calculate Square Root
- User Input | Input () Function | Keyboard Input
- Best Book to Learn Python
Conclusion
The time complexity of the python max function is O(n). Unlike max functions in other programming languages like C++, it offers a variety of uses. We can apply it on the string, which is not possible in other languages. These types of built-in functions make python a great language.
Try to run the programs on your side and let me know if you have any queries.
Happy Coding!
HI, How to use max function in a real time data.
You might need to use max() every time the data updates. For this, you can store a temporary data and compare the new data everytime with temp data. If its different then use max() and update the temp data to current data.
Regards,
Pratik