DEV Community

hrishikesh1990
hrishikesh1990

Posted on • Edited on • Originally published at flexiple.com

Python Max Function - All you need to know

In this short tutorial, we look at the different ways the Python Max function can be used. We also have a section where we look at the code for each section to help facilitate further understanding.

This tutorial is a part of our initiative at Flexiple, to write short curated tutorials around often used or interesting concepts.

Table of Content

Where can the 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.

Syntax 1:

max(arg1, arg2,)
Enter fullscreen mode Exit fullscreen mode

Parameters:

arg1, arg2 are values that you are looking to compare, could be a number or a string.

Code:

print(max(1,2,3,4,5))

//Output - 5
Enter fullscreen mode Exit fullscreen mode

We shall look at the other syntax, while looking at iterables.

Using Max on Iterables

In this section we look at how the 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.

Syntax:

max(iterable, default)
Enter fullscreen mode Exit fullscreen mode

Parameter:

Iterables - Commonly used ones are - lists, dictionaries, tuples, strings.

Default - This value is returned in case the iterable is empty

Code:

// Lists
l1 = [5, 10, 15, 20, 25]
print(max(l1));
// Output: 25

//Tuples
t1 = (50, 100, 150)
print(t1);
// Output: 150
Enter fullscreen mode Exit fullscreen mode

While using the function on a dictionary, the largest key is returned.

//Dictionaries
d1 = {5: -5, -10: 10, 20: 15, 22: 4}
print(max(d1))

// Output: 22
Enter fullscreen mode Exit fullscreen mode

While using the function on a list of strings the strings are ordered alphabetically and the largest string is returned.

s1 = ["hire", "the", "top", "freelancers"]
print(max(s1))

// Output = "top"
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)