Yandex

Python max() Function – Find the Largest Value



Python max() Function

The max() function in Python is used to find the largest item in an iterable (like a list, tuple, set) or among two or more arguments. It’s one of the most common functions used in comparisons, data analysis, and sorting tasks.

Syntax

max(iterable, *[, key, default])
max(arg1, arg2, *args[, key])

Parameters:

  • iterable – A list, tuple, set, or any iterable.
  • arg1, arg2, *args – Two or more values to compare.
  • key (optional) – A function to customize sorting logic.
  • default (optional) – A value to return if the iterable is empty.

Returns:

  • The largest value among the inputs.

Example 1: Find the Maximum in a List

numbers = [5, 12, 3, 8]
print(max(numbers))
12

Example 2: Compare Multiple Arguments

print(max(10, 25, 3, 99))
99

Example 3: Using key with Strings

words = ["apple", "banana", "pear", "mango"]
print(max(words, key=len))
banana

Why? The key=len means it compares word lengths, not alphabetical order.

Example 4: Using default with an Empty Iterable

empty = []
print(max(empty, default=0))
0

Use Cases

  • Finding the highest score, price, or value
  • Selecting the longest string or list
  • Working with custom objects (using key functions)

Common Mistakes

  • Calling max([]) without default will raise a ValueError
  • Comparing incompatible types will raise a TypeError

Interview Tip

The max() function is often used in DSA problems like finding the max subarray, longest word, or highest frequency. Learn how to combine it with key and lambda.

Summary

  • max() returns the largest value from arguments or iterable.
  • You can customize comparison using the key parameter.
  • Use default to avoid errors on empty iterables.

Practice Problem

Write a program that takes three numbers from the user and prints the largest one.

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
print("Largest number is:", max(a, b, c))


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M