Yandex

Python min() Function – Find the Smallest Value



Python min() Function

The min() function in Python returns the smallest item from a list, tuple, or multiple values passed to it. It is one of the most useful built-in functions for comparing and analyzing data.

Syntax

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

Parameters:

  • iterable: A sequence (like list, tuple, set, etc.) of comparable items.
  • arg1, arg2, *args: Two or more values for direct comparison.
  • key (optional): A function to customize the comparison logic.
  • default (optional): Value to return if the iterable is empty (used only with default keyword).

Returns:

  • The smallest item based on natural or key-based ordering.

Example 1: Smallest in a List

numbers = [10, 5, 22, 3, 19]
print(min(numbers))
3

Example 2: Comparing Multiple Values

print(min(4, 1, 7, -2, 9))
-2

Example 3: Smallest String in List

words = ["banana", "apple", "cherry"]
print(min(words))
apple

Note: Strings are compared lexicographically (alphabetical order).

Example 4: Using key Parameter

Find the shortest word based on length:

words = ["elephant", "cat", "hippopotamus"]
shortest = min(words, key=len)
print(shortest)
cat

Example 5: Using default with Empty Iterable

empty = []
result = min(empty, default=0)
print(result)
0

Common Mistakes

  • Calling min([]) without a default will raise a ValueError.
  • Comparing incompatible types like strings and numbers will raise a TypeError.

Use Cases

  • Find the minimum score, price, or measurement
  • Identify the earliest date or lowest temperature
  • Sort and filter data by smallest criteria

Interview Tip

min() is frequently used in problems involving optimization, such as finding the minimum distance, cost, or value in arrays.

Summary

  • min() returns the smallest item from a sequence or arguments
  • Supports key for custom comparison
  • Use default to avoid errors with empty iterables

Practice Problem

Write a program that reads five numbers from the user and prints the smallest one.

nums = [int(input("Enter a number: ")) for _ in range(5)]
print("Smallest number is:", min(nums))


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