How to use the min() function in Python

Learn how to use Python's min() function with our guide. Discover different methods, tips, real-world applications, and common error fixes.

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

Python's min() function is a simple yet essential tool. It efficiently finds the smallest item within an iterable or compares multiple arguments to identify the minimum value.

In this article, you'll explore several techniques to use min(). We'll cover practical tips, real-world applications, and advice to debug common issues so you can apply this versatile function effectively.

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 straightforward use of the min() function. By passing the list numbers directly to min(), you're asking Python to iterate through the collection and return the single lowest value it finds, which is 7 in this case.

This approach is clean and highly readable. It saves you from writing a loop to manually compare each element, making your code more concise and less prone to errors. It's the go-to method when you need the smallest item from any iterable like a list, tuple, or set.

Basic applications of min()

While min() is perfect for simple number lists, its real power shines when you apply it to more complex data types and custom sorting logic.

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

The min() function isn't limited to finding the smallest item in a list. You can also pass multiple arguments directly to it, and it will return the lowest value among them.

  • When given min(10, 5, 20), it correctly identifies 5 as the smallest integer.
  • It works just as well with floats, returning 1.618 from min(3.14, 2.71, 1.618).

This is a handy shortcut when you need to compare a few distinct values without first bundling them into a collection.

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 you pass strings to min(), it performs an alphabetical comparison by default. That’s why it returns "apple". But the function's real flexibility comes from the key argument, which lets you define a custom rule for comparison.

  • By using key=len, you're telling min() to evaluate each string's length instead of its alphabetical value.
  • This simple change allows it to correctly identify "java" as the shortest string in the second example.

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 becomes even more powerful when you use it with complex data structures like a list of tuples. Here, you're not just finding the smallest number; you're finding the "smallest" tuple based on a specific criterion.

  • The lambda function, lambda person: person[1], creates a simple, on-the-fly instruction for the comparison.
  • It tells min() to ignore the names and focus only on the second element of each tuple—the age.
  • Based on this rule, min() finds the tuple with the lowest age and returns the entire item, ("Charlie", 22).

Advanced usage of min()

Building on the key parameter's flexibility, you can also use min() to compare custom objects, provide default values, and efficiently process data with iterators and generators.

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 isn't limited to built-in data types; you can use it on your own custom objects, too. The key is providing a function that tells min() which attribute to compare.

  • The lambda p: p.price function instructs min() to look at the price attribute of each Product object.
  • Instead of comparing the objects themselves, Python compares their prices to find the minimum.

This returns the entire Product object with the lowest price, making it a powerful way to sort complex data structures.

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 the min() function on an empty sequence raises a ValueError because there's no item to return. The code first demonstrates this common pitfall inside a try...except block.

To handle this gracefully, you can use the default parameter. By setting a default value, you tell min() what to return if the iterable is empty. This approach avoids the error entirely, making your code more robust and predictable without needing extra error-handling logic.

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 especially powerful when paired with generators because it processes data without storing it all in memory. This is a huge advantage for memory efficiency, particularly with large datasets.

  • The code uses a generator expression—(x for x in ...)—to filter values from the squares generator on the fly.
  • min() pulls just one value at a time, compares it, and efficiently finds the smallest positive even square.

This approach keeps your code lean and performant.

Move faster with Replit

Replit is an AI-powered development platform that transforms natural language into working applications. Describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.

For the min() techniques we've explored, Replit Agent can turn them into production tools:

  • Build a price comparison tool that finds the cheapest item from a list of products.
  • Create a data validation utility that identifies the record with the lowest value in a dataset, like finding the employee with the fewest open tickets.
  • Deploy a leaderboard that displays the user with the fastest time from a list of game scores.

Describe your app idea, and Replit Agent writes the code, tests it, and fixes issues automatically. Start building your next project with Replit Agent.

Common errors and challenges

While min() is powerful, you can run into a few common issues if you're not careful.

  • Handling type errors when comparing different data types with min()
  • One of the most frequent errors is the TypeError, which occurs when you try to compare incompatible data types. For instance, calling min() on a list containing both numbers and strings will fail because Python doesn't have a default rule for deciding whether an integer is "smaller" than a string. Always ensure all items you're comparing are of the same or comparable types.
  • Forgetting to provide a key function for complex objects
  • When you work with lists of custom objects, `min()` doesn't automatically know how to compare them. If you forget to specify which attribute to use for the comparison via the key parameter, Python will raise a TypeError. You must provide a function to the key argument that extracts a comparable value, like an object's price or age.
  • Dealing with None values in sequences
  • The presence of None in a sequence can also cause a TypeError, as None cannot be compared to other data types like integers or strings. A common way to handle this is to filter out any None values before passing the sequence to min(). Alternatively, you can use a key function to define how None should be treated during the comparison.

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

Mixing data types like numbers and strings in a single list is a recipe for a TypeError when using min(). Since Python can't logically compare 42 and "hello", it stops execution. The following code demonstrates this common pitfall in action.

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

The code attempts to compare fundamentally different things: numbers and text. Python's min() function can't decide if 42 is "less than" "hello", which causes a TypeError. The corrected code below demonstrates one way to handle this.

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

The fix is simple: don't mix your data. The corrected code separates the numbers and strings into their own lists. By calling min() on each list individually, you ensure that comparisons are always like-for-like. This avoids the TypeError entirely. It's a good practice to always check your data types before passing them to functions like min() or max() to prevent unexpected crashes, especially when dealing with data from external sources.

Forgetting to provide a key function for complex objects

When working with complex objects like dictionaries, Python's min() function doesn't know which value to compare. Without a key function to guide it, Python can't determine if one dictionary is "smaller" than another, leading to a TypeError. The following code illustrates what happens when you forget to provide this crucial instruction.

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 code fails because min() attempts to directly compare two dictionary objects. Python doesn't have a built-in rule for this comparison, which triggers a TypeError. The corrected code below shows how to provide the right instructions.

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 fix is to tell min() exactly what to compare using the key parameter. The function lambda s: s["grade"] instructs min() to look only at the value of the "grade" key in each dictionary. This allows it to compare the numbers (85 and 92) instead of the dictionaries themselves, avoiding the error. You'll need this approach whenever you're sorting complex objects, like data from an API or database.

Dealing with None values in sequences

Encountering a None value in a sequence is a common challenge. Since None can't be compared to numbers or strings, the min() function will raise a TypeError, stopping your code. The example below shows this error in action.

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

The code fails because min() can't compare numbers like 10 and 5 with None. Since Python has no rule for this comparison, it raises a TypeError. The corrected code below shows how to fix 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 to simply remove any None values before calling min(). The code does this with a list comprehension—[v for v in values if v is not None]—to generate a clean list. Passing this filtered list to min() ensures that only comparable items are evaluated, preventing a TypeError. You'll find this technique essential when handling data from sources like databases or APIs, where missing values are common.

Real-world applications

With those common errors handled, you can use min() to solve complex problems like finding the closest location or the best investment.

Finding the closest location using min()

By pairing min() with a key that calculates distance, you can easily find the closest geographical point from a list 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 code snippet cleverly finds the nearest city to a specific point. It leverages the min() function not on the cities themselves, but on the calculated distance to each one.

  • The key argument is assigned a lambda function that computes the Euclidean distance between the current_location and each city's coordinates.
  • min() iterates through the cities dictionary, using this distance as the comparison value for each item.

As a result, it returns the city-coordinate pair with the smallest distance, effectively identifying the closest geographical point from the list.

Finding optimal investment using min()

By defining a custom function to score investments based on risk and return, you can use min() to pinpoint the optimal choice from a complex dataset.

# 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 finds the best investment by applying custom logic. The min() function uses the risk_adjusted_score function as its key to evaluate each option.

  • The risk_adjusted_score function creates a single metric where a lower score is better. It balances risk factors like volatility against the potential reward.
  • min() then iterates through the list, calling this function for each investment to get its score.
  • It returns the entire dictionary for the investment that yields the lowest score, effectively finding the most optimal choice based on your defined criteria.

Get started with Replit

Turn your knowledge of min() into a real tool. Describe what you want to Replit Agent, like: “Find the cheapest product from a list” or “Identify the data point with the lowest value.”

The agent writes the code, tests for errors, and deploys your app. Start building with Replit.

Get started free

Create and 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.

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.