Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 13, 2021 11:26 am GMT

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.

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 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.

Syntax 1:

max(arg1, arg2,)

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

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

Using Max on Iterables

In this section, 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.

Syntax:

max(iterable, default)

Parameter:

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

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

Code:

// Listsl1 = [5, 10, 15, 20, 25]print(max(l1));// Output: 25//Tuplest1 = (50, 100, 150)print(t1);// Output: 150

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

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

While using the python max 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"

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

Original Link: https://dev.to/hrishikesh1990/how-to-use-the-python-max-function-51go

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To