Python min() function


The min() function in Python returns the smallest item in an iterable (such as a list, tuple, or string) or the smallest of two or more arguments.

Syntax

min(iterable, *[, key, default]) min(arg1, arg2, *args[, key])
  • iterable: An iterable (e.g., list, tuple, string) from which the minimum value is found.
  • arg1, arg2, *args: If multiple arguments are passed, min() returns the smallest of these values.
  • key (optional): A function to determine how to compare the elements. It takes a function that returns a value to use for comparison.
  • default (optional): If the iterable is empty and default is provided, it returns the default value instead of raising an error.

Return Value

  • Returns the smallest item from the provided iterable or among the provided arguments.
  • If the iterable is empty and no default is provided, a ValueError is raised.

Examples

  1. Using min() with a list of numbers:

    numbers = [1, 5, 3, 9, 2] print(min(numbers)) # Output: 1
  2. Using min() with multiple arguments:

    print(min(10, 20, 30)) # Output: 10
  3. Using min() with a string: When used with a string, min() returns the character with the smallest Unicode value.

    print(min("hello")) # Output: 'e'
  4. Using min() with a key function: You can use the key argument to specify a function that extracts a comparison key from each element.

    words = ["apple", "banana", "cherry"] print(min(words, key=len)) # Output: 'apple' (shortest word)
  5. Using min() with tuples:

    points = [(2, 5), (1, 9), (4, 7)] print(min(points)) # Output: (1, 9) (compares based on the first value)
  6. Using min() with an empty iterable and default: If the iterable is empty, you can provide a default value to avoid an error.

    empty_list = [] print(min(empty_list, default=0)) # Output: 0
  7. Finding the minimum in a dictionary by values: You can use min() with a key to find the key with the smallest value.

    scores = {"Alice": 10, "Bob": 20, "Charlie": 15} print(min(scores, key=scores.get)) # Output: 'Alice' (smallest score)

Summary

  • The min() function finds the smallest value in an iterable or among several arguments.
  • You can customize the comparison using the key argument, and provide a default value for empty iterables.
  • It works with various data types like numbers, strings, tuples, and even dictionaries.