How to use the min() function in Python

Learn how to use Python's min() function with examples, tips, real-world applications, and common error fixes. Master this essential tool.

How to use the min() function in Python
Published on: 
Tue
Mar 10, 2026
Updated on: 
Wed
Apr 1, 2026
The Replit Team

Python's min() function is a powerful tool that finds the smallest item in an iterable or among several arguments, simplifying data comparison and analysis tasks.

In this article, we'll cover techniques to use min() effectively with various data types. You'll get practical tips, see real-world applications, and learn debugging advice to master this function.

Using basic min() function

numbers = [42, 23, 7, 19, 36]
smallest = min(numbers)
print(f"The smallest number is: {smallest}")--OUTPUT--The smallest number is: 7

The code demonstrates the most direct application of the min() function. It takes a single iterable—in this case, the list numbers—and returns the smallest item. This is far more efficient than writing a manual loop to iterate and compare each element yourself.

The function processes the entire collection, identifies the lowest value, 7, and assigns it to the smallest variable. This approach is clean, readable, and the standard way to find a minimum value within a sequence of comparable items like numbers or strings.

Basic applications of min()

Beyond simple numbers, the min() function also handles strings and adapts to complex data structures with the powerful key parameter.

Using min() with different data types

integers = min(10, 5, 20)
floats = min(3.14, 2.71, 1.618)
print(f"Minimum integer: {integers}, Minimum float: {floats}")--OUTPUT--Minimum integer: 5, Minimum float: 1.618

You're not limited to passing a single iterable to min(). The function can also directly compare two or more arguments, handling various numeric types without extra configuration. This dual functionality makes it incredibly flexible for quick comparisons.

  • When given min(10, 5, 20), it correctly identifies 5 as the smallest integer.
  • Similarly, with floating-point numbers like min(3.14, 2.71, 1.618), it returns 1.618.

Using min() with strings

result1 = min("apple", "banana", "cherry")
result2 = min("python", "java", "golang", key=len)
print(f"Alphabetically first: {result1}")
print(f"Shortest string: {result2}")--OUTPUT--Alphabetically first: apple
Shortest string: java

When used with strings, min() defaults to lexicographical—or alphabetical—comparison. That’s why min("apple", "banana", "cherry") returns "apple", as it would appear first in a dictionary.

  • The key parameter lets you define a custom sorting logic. By passing key=len, you're telling the function to find the minimum value based on the length of each string.
  • This is how min("python", "java", "golang", key=len) correctly identifies "java" as the shortest string in the sequence.

Using min() with the key parameter

people = [("Alice", 25), ("Bob", 30), ("Charlie", 22)]
youngest = min(people, key=lambda person: person[1])
print(f"Youngest person: {youngest[0]}, Age: {youngest[1]}")--OUTPUT--Youngest person: Charlie, Age: 22

The key parameter truly shines when working with complex data structures like lists of tuples. It lets you specify exactly what to compare. In this case, the lambda function tells min() to ignore the names and focus only on the second element of each tuple—the age.

  • The expression key=lambda person: person[1] defines a small, anonymous function that extracts the age from each tuple.
  • min() then uses these extracted ages (25, 30, and 22) to perform its comparison.
  • Because 22 is the lowest age, the function returns the entire original tuple associated with it: ("Charlie", 22).

Advanced usage of min()

Building on the key parameter, you can extend min() to handle custom objects, provide default values for empty inputs, and work efficiently with iterators.

Using min() with custom objects

class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def __repr__(self):
return f"{self.name}: ${self.price}"

products = [Product("Laptop", 1200), Product("Phone", 800), Product("Tablet", 500)]
cheapest = min(products, key=lambda p: p.price)
print(f"Cheapest product is {cheapest}")--OUTPUT--Cheapest product is Tablet: $500

The min() function works seamlessly with custom objects, provided you tell it what to compare. By default, Python doesn't know whether to compare a Product by its name or price. This is where the key parameter is essential.

  • The expression key=lambda p: p.price instructs min() to look only at the price of each object.
  • The function then identifies the object with the lowest price and returns the entire Product instance, not just the price value.

Using min() with default values

empty_list = []
try:
result = min(empty_list)
except ValueError as e:
print(f"Error: {e}")

safe_min = min(empty_list, default="No items found")
print(f"Safe result: {safe_min}")--OUTPUT--Error: min() arg is an empty sequence
Safe result: No items found

Calling min() on an empty sequence normally triggers a ValueError because there are no items to compare. The default parameter offers a clean way to handle this scenario without needing a try...except block every time. It provides a fallback value that the function returns if the iterable is empty, preventing your program from crashing.

  • The code first demonstrates the ValueError that occurs with an empty list.
  • By setting default="No items found", the function safely returns that string instead of an error, making your code more robust.

Using min() with iterators and generators

def squares(n):
for i in range(n):
yield i ** 2

smallest_even_square = min((x for x in squares(10) if x % 2 == 0 and x > 0))
print(f"Smallest positive even square: {smallest_even_square}")--OUTPUT--Smallest positive even square: 4

The min() function is highly efficient with generators because it processes values one at a time without storing the entire sequence in memory. This is ideal for large datasets where creating a full list would be impractical.

  • The code uses a generator expression, (x for x in squares(10) if x % 2 == 0 and x > 0). This expression pulls values from the squares generator and filters for positive, even numbers.
  • min() consumes these filtered values as they're generated (4, 16, 36, 64) and identifies 4 as the smallest, all without building a complete list.

Move faster with Replit

Replit is an AI-powered development platform that lets you start coding Python instantly. It comes with all dependencies pre-installed, so you can skip environment setup and get straight to building.

While knowing individual functions like min() is essential, the real power comes from using them to build complete applications. That's where Agent 4 comes in, helping you move from individual techniques to a finished product.

  • A price-finder that sorts through a list of products to find the most affordable option.
  • An SEO tool that analyzes headline variations and returns the shortest one for better engagement.
  • A simple scheduling assistant that identifies the earliest open meeting time in a calendar.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

While min() is straightforward, you can run into a few common pitfalls, especially when working with mixed data types or complex objects.

The most frequent issue is a TypeError, which happens when you ask min() to compare incompatible items. Python can't decide if 10 is smaller than "hello", so it raises an error. To avoid this, you must ensure all items in your sequence are comparable with each other.

  • Forgetting the key function: When working with complex objects, you must tell min() what to compare. If you pass a list of objects without a key to specify an attribute like price or age, Python doesn't know how to rank them and will raise an error.
  • Comparing different data types: Calling min() on a list containing mixed, incompatible types like [1, "two", 3] will fail. Always ensure your data is uniform enough to be compared.
  • Dealing with None values: The None value can't be compared to other data types. If your sequence might contain None, you need to filter these values out before calling min() to prevent your code from crashing.

Handling type errors when comparing different data types with min()

A TypeError is the most common issue you'll face with min(). It occurs when the function tries to compare incompatible types, like an integer and a string. Python can't decide if 42 is smaller than "hello". The following code demonstrates this error.

numbers_and_strings = [42, "hello", 7, "python"]
smallest = min(numbers_and_strings)
print(f"The smallest value is: {smallest}")

The code fails because it's trying to find the minimum in a list with both integers and strings. Python can't determine if 42 is smaller than "hello", causing a TypeError. The following example shows how to fix this.

numbers = [42, 7, 10]
strings = ["hello", "python", "code"]
print(f"Smallest number: {min(numbers)}, Smallest string: {min(strings)}")

The solution is to segregate your data by type before comparison. By splitting the mixed list into separate lists for numbers and strings, you can call min() on each one individually. This ensures the function only compares compatible items—integers with integers and strings with strings. You'll often encounter this issue when processing raw data from files or APIs, which can contain inconsistent types that need to be cleaned up first.

Forgetting to provide a key function for complex objects

Another common pitfall is giving min() a list of complex objects, like dictionaries, without telling it what to compare. Python can't guess whether to sort by a student's name or grade, so it raises a TypeError. The following code demonstrates this exact issue.

students = [{"name": "Alice", "grade": 85}, {"name": "Bob", "grade": 92}]
lowest_grade_student = min(students)
print(f"Student with lowest grade: {lowest_grade_student['name']}")

The min() function can't compare two dictionary objects without instructions. This ambiguity causes a TypeError. The following code provides the necessary guidance to make the comparison work correctly.

students = [{"name": "Alice", "grade": 85}, {"name": "Bob", "grade": 92}]
lowest_grade_student = min(students, key=lambda s: s["grade"])
print(f"Student with lowest grade: {lowest_grade_student['name']}")

The solution is to provide a comparison rule using the key parameter. This tells min() exactly what to compare.

  • The expression key=lambda s: s["grade"] instructs the function to look only at the value of the "grade" key in each dictionary.

This resolves the ambiguity, allowing the function to correctly identify the student with the lowest grade. You'll often need this when working with lists of dictionaries, such as when processing JSON data from an API.

Dealing with None values in sequences

Your data isn't always clean, and None values are a frequent problem. Since None can't be compared to numbers or strings, using min() on a sequence containing it will trigger a TypeError. The code below shows what happens when you try.

values = [10, 5, None, 20]
smallest = min(values)
print(f"The smallest value is: {smallest}")

The code fails because min() hits a TypeError when it tries comparing a number with None. Python doesn't know how to rank None against an integer. The next example shows how to work around this.

values = [10, 5, None, 20]
valid_values = [v for v in values if v is not None]
smallest = min(valid_values)
print(f"The smallest value is: {smallest}")

The fix is simple: filter out None values before calling min(). The code uses a list comprehension, [v for v in values if v is not None], to create a new list containing only the numbers. This pre-processing step ensures min() receives a clean sequence of comparable items, avoiding the TypeError. Keep an eye out for this issue when handling data from databases or APIs, where missing values are often represented as None.

Real-world applications

With error handling mastered, min() becomes a powerful tool for solving complex problems in logistics, finance, and beyond.

Finding the closest location using min()

You can combine min() with a custom distance formula in the key parameter to efficiently find the nearest point of interest from a set of coordinates.

# Coordinates (latitude, longitude) of cities
cities = {
"New York": (40.7128, -74.0060),
"Los Angeles": (34.0522, -118.2437),
"Chicago": (41.8781, -87.6298),
"Houston": (29.7604, -95.3698)
}

# User's current location
current_location = (39.9526, -75.1652) # Philadelphia

# Find closest city using Euclidean distance
closest_city = min(cities.items(),
key=lambda city: ((city[1][0] - current_location[0])**2 +
(city[1][1] - current_location[1])**2)**0.5)

print(f"Closest city: {closest_city[0]}")
print(f"Distance: {((closest_city[1][0] - current_location[0])**2 + (closest_city[1][1] - current_location[1])**2)**0.5:.2f} degrees")

This example demonstrates how to find the closest geographical point from a list. The code iterates through a dictionary of cities using cities.items() and applies a custom comparison logic with the min() function.

  • The key parameter is set to a lambda function that calculates the Euclidean distance between the current_location and each city's coordinates.

By doing this, min() doesn't compare the city names or coordinates directly. Instead, it finds the city for which the calculated distance is the smallest, effectively identifying the nearest location.

Finding optimal investment using min()

In financial modeling, you can use min() to find the investment with the best risk-to-return ratio by providing a custom function that calculates a score for each option.

# Investment options with risk and return metrics
investments = [
{"name": "Stock A", "volatility": 0.15, "expected_return": 0.12, "liquidity_risk": 0.05},
{"name": "Bond B", "volatility": 0.05, "expected_return": 0.06, "liquidity_risk": 0.02},
{"name": "Fund C", "volatility": 0.10, "expected_return": 0.09, "liquidity_risk": 0.03},
{"name": "Stock D", "volatility": 0.20, "expected_return": 0.15, "liquidity_risk": 0.07}
]

# Risk-adjusted metric (lower is better)
def risk_adjusted_score(inv):
risk_score = inv["volatility"] + inv["liquidity_risk"]
return risk_score / inv["expected_return"]

safest_investment = min(investments, key=risk_adjusted_score)

print(f"Best risk-adjusted investment: {safest_investment['name']}")
print(f"Return: {safest_investment['expected_return']}, Volatility: {safest_investment['volatility']}")
print(f"Risk-adjusted score: {risk_adjusted_score(safest_investment):.2f}")

This code evaluates several investments to identify the one with the optimal balance of risk and reward. It does this by passing a custom function, risk_adjusted_score, to the min() function's key parameter.

  • The risk_adjusted_score function defines what "best" means—in this case, a low score derived from volatility, liquidity, and return.
  • min() iterates through the investments list, applies this scoring function to each dictionary, and returns the one with the lowest score, making it a flexible tool for custom decision-making.

Get started with Replit

Turn your knowledge of the min() function into a real tool. Just tell Replit Agent: "Find the cheapest product from a list of dictionaries" or "Build a script to find the closest GPS coordinate."

Replit Agent writes the code, tests for errors, and deploys the app. It's the fastest way to turn your instructions into a working application. Start building with Replit.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.

Get started for free

Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.