Python max() Function: Return The Largest Item In An Iterable

by | Python

When working with data in Python, you must perform different operations to extract meaningful information. Python offers a wide range of built-in functions to perform various operations. One such function is the Python max() function, which proves invaluable when working with large datasets.

The max() function in Python is a built-in function that returns the largest item in an iterable or the largest of two or more arguments. If you provide multiple individual values, it returns the maximum value among them. If you provide an iterable, like a list or a tuple, it returns the maximum value found within that iterable.

Python max() Function

With Python’s max() function, you can streamline your code and improve its readability while dealing with various data types and use cases. In this article, we’ll get you started in using the Python max() function. We’ll review multiple scenarios where the max() function proves invaluable.

Let’s get into it!

Syntax of Python max() Function

The max() function has two main forms of syntax.

  1. Syntax for arguments
  2. Syntax for iterable

1) Syntax for Arguments

The first form finds the largest item between two or more arguments. When using max() without the iterable, it returns the largest object among the parameters passed.

The syntax looks like the following:

max(arg1, arg2, *args, key)

In this syntax, arg1, arg2, and any additional arguments are passed and comparison is performed based on its return value default. The optional key parameter can be used to specify a function that the input arguments are passed through before making the comparison.

2) Syntax for Iterable

You can use the second form to find the largest item in an iterable, such as a list or a set.

The syntax for this form looks like this:

max(iterable, key, default)

Here, the iterable parameter refers to the input iterable object that needs to be searched for the maximum value.

Similar to the first form, you can use the key parameter to specify a custom function. The default parameter is optional and sets a default return value if the iterable is empty.

Basic Examples of max() Function

After understanding the syntax of the Python max() function, let’s put what we learned so far into a test. In this section, we’ll cover some basic examples of using the max() function with different data types.

Basic Examples of max() Function

We’ll use both the syntax discussed above to get you started with using the max() function in your projects.

Example 1: Using max() With Numbers

You can use the max() function with numbers to find the maximum number. You simply pass the numbers as arguments to the function. Without specifying any arguments, the max() will use the default value of the function.

The following code example demonstrates this method:

# Define three numbers
num1 = 10
num2 = 20
num3 = 30

# Use max() to find the maximum number
max_num = max(num1, num2, num3)

print("The maximum number is", max_num)

In this case, max() takes the numbers 10, 20, and 30 as arguments and returns the largest one, which is 30. So, the output of the program will be “The maximum number is 30”.

Using max() with numbers

Example 2: Finding the Maximum Item in a List

You can also use the max() function to find the maximum item in a list.

The following is an example of this method:

# Define a list of numbers
numbers = [4, 2, 9, 6, 5, 1, 8, 3, 7]

# Use max() to find the maximum number in the list
max_num = max(numbers)

print("The maximum number in the list is", max_num)

In this case, max() takes a list of numbers as an argument and returns the largest one in the list, which is 9. So, the output of the program will be “The maximum number in the list is 9”.

Finding the maximum item in a list

Example 3: Finding The Maximum Item in a Tuple

The max() function can be applied to tuples in a similar manner to lists.

The following is an example:

# Define a tuple of numbers
numbers = (4, 2, 9, 6, 5, 1, 8, 3, 7)

# Use max() to find the maximum number in the tuple
max_num = max(numbers)

print("The maximum number in the tuple is", max_num)

In this case, max() takes a tuple of numbers as an argument and returns the max value in the tuple, which is 9.

The function will print max value to the console.

Finding The Maximum Item in a Tuple

Example 4: Comparison of Strings

You can also use the max() function to compare strings. It considers the lexicographic order of the strings, based on the ASCII value of the characters.

The following is an of this method:

# Define three strings
str1 = "Apple"
str2 = "Banana"
str3 = "Cherry"

# Use max() to find the "maximum" string
max_str = max(str1, str2, str3)

print("The maximum string is", max_str)

In this case, max() compares the strings “Apple”, “Banana”, and “Cherry”. It returns the lexicographically maximum character, which is “Cherry”.

So, the output of the program will be “The maximum string is Cherry”. The comparison is case-sensitive and uppercase letters have lower ASCII values than lowercase ones.

Comparison of Strings

How to Use the Key Argument in max() Function

The max() function allows using a key function that helps customize the comparison process. The key argument accepts a callable function like int(), len(), ord(), or even a custom user-defined function.

How to Use The Key Argument in max() Function

In this section, we’ll go over four examples of customizing the key argument for different scenarios.

Example 1: Using int() as a Key Argument in max()

Let’s say we have a list of strings representing numbers and we want to find the maximum numerical value. We can use int() as a key function to convert these strings into integers for comparison.

# Define a list of string numbers
str_nums = ['4', '2', '9', '6', '5']

# Use max() with int as a key function
max_num = max(str_nums, key=int)

print("The maximum number is", max_num)

This will output “The maximum number is 9”, because max() is comparing the string numbers as integers.

Using int() as a Key Argument in max()

Example 2: Using len() as a Key Argument in max()

If we want to find the string with the maximum length in a list of strings, we can use len() as a key function.

You can pass multiple iterables, as shown in the example below:

# Define a list of strings
strings = ['apple', 'banana', 'cherry', 'date']

# Use max() with len as a key function
max_str = max(strings, key=len)

print("The longest string is", max_str)

This will output “The longest string is banana”, because banana has the most characters.

Using len() as a Key Argument in max()

Example 3: Using ord() as a Key Argument in max()

The ord() function returns an integer representing the Unicode character.

If we have a list of single-character strings and want to find the one with the highest Unicode value, we can use ord() as a key function.

# Define a list of characters
chars = ['a', 'b', 'c', 'z']

# Use max() with ord as a key function
max_char = max(chars, key=ord)

print("The character with the highest Unicode value is", max_char)

This will output “The character with the highest Unicode value is z”, because ‘z’ has the highest Unicode value in the list.

Using ord() as a Key Argument in max()

Example 4: Using a Custom Function as a Key Argument in max()

Let’s say we have a list of tuples where each tuple represents a 2D point with x and y coordinates.

If we want to find the point with the largest distance from the origin, we can create a custom function to calculate this distance and use it as a key function.

The following Python code demonstrates this use case:

import math

# Define a list of 2D points
points = [(1, 1), (3, 3), (2, 2), (4, 4)]

# Define a custom function to calculate the distance from the origin
def distance(point):
    return math.sqrt(point[0]**2 + point[1]**2)

# Use max() with distance as a key function
max_point = max(points, key=distance)

print("The point with the largest distance from the origin is", max_point)

This will output “The point with the largest distance from the origin is (4, 4)“, because (4, 4) is the furthest point from the origin in the list according to Euclidean distance.

 Using a Custom Function as a Key Argument in max()

How to Apply max() Function to Pandas DataFrame

Pandas is a powerful data manipulation library. When you apply a max() function to a Pandas DataFrame, you can find the maximum value across a specified axis.

How to Apply max() Function to Pandas DataFrame

The two options for axis parameters are:

  1. axis=0 (index): Computes the maximum value for each column.
  2. axis=1 (columns): Computes the maximum value for each row.

1) How to Find The Maximum Value For Each Column

Consider the following DataFrame example:

import pandas as pd

data = {
    "A": [12, 4, 5, 44, 1],
    "B": [5, 2, 54, 3, 2],
    "C": [20, 16, 7, 3, 8],
    "D": [14, 3, 17, 2, 6]
}

df = pd.DataFrame(data)

The DataFrame looks like the following:

Dataframe under analysis

To find the largest value for each column (axis=0), you can use the following code:

column_max = df.max(axis=0)

This will return a Series with the maximum values for each column.

Finding maximum values for each column

2) How to Find The Maximum Value For Each Row

If you want to find the maximum value for each row (axis=1), you can use the following code:

row_max = df.max(axis=1)

This will return a Series with the maximum values for each row.

Finding maximum values for each row

Learn more about functions in Python by watching the following video:

Final Thoughts

The Python max() function is a powerful tool that allows you to extract maximum values with minimal effort. Whether you’re working with numbers, strings, or complex data structures, max() offers a quick way to identify the highest element.

Moreover, with the added flexibility of the key argument, max() becomes incredibly versatile. It allows you to customize what ‘maximum’ means in different contexts. The max() is your go-to function if you are searching for the longest word in a text, the highest score in a game, or the furthest point in a set of coordinates.

Frequently Asked Questions

Frequently Asked Questions

What are the different ways to use max() function in Python?

There are two main ways to use the max() function in Python.

The first one is by passing multiple arguments, like numbers or strings, and the function will return the highest value among them.

For example:

result = max(10, 20, 40)

The second way is to pass an iterable, such as a list or tuple, as the argument, and the function will return the highest value within that iterable.

For example:

my_list = [1, 2, 3, 4, 5]
result = max(my_list)

How to find the maximum value in a list using max()?

To find the maximum value in a list, simply pass the list as the argument to the max() function.

Here’s an example:

my_list = [4, 3, 8, 1, 12]
max_value = max(my_list)

In this case, max_value would be 12.

Can max() be used with dictionaries in Python?

Yes, the max() function can be used with dictionaries. By default, it will compare the keys and return the key with the highest value.

To get the maximum value based on the dictionary values, use the key parameter:

my_dict = {'a': 10, 'b': 25, 'c': 15}
max_key = max(my_dict, key=my_dict.get)

In this example, max_key would be ‘b’.

How does min() function relate to the max() function in Python?

The min() function works similarly to the max() function but instead of returning the highest value, it returns the smallest value among the input arguments or within an iterable.

How to get the index of the maximum value using max()?

To get the index of the maximum value in a list or sequence, use the enumerate() function along with the max() function and a lambda as the key.

Here’s an example:

my_list = [4, 3, 10, 5, 2]
max_index = max(enumerate(my_list), key=lambda x: x[1])[0]

In this case, max_index would be 2.

Related Posts