Skip to content

Python Minimum: Effortlessly Find the Smallest Value in a List

[

Python’s min() and max(): Find Smallest and Largest Values

Python’s built-in min() and max() functions come in handy when you need to find the smallest and largest values in an iterable or in a series of regular arguments. These functions may seem basic, but they have many interesting use cases in real-world programming. In this tutorial, you will learn how to utilize Python’s min() and max() functions in various scenarios.

In this tutorial, you’ll learn how to:

  1. Use Python’s min() and max() to find the smallest and largest values in your data.
  2. Call min() and max() with a single iterable or with any number of regular arguments.
  3. Use min() and max() with strings and dictionaries.
  4. Tweak the behavior of min() and max() with the key and default arguments.
  5. Use comprehensions and generator expressions as arguments to min() and max().

Once you have a good understanding of these concepts, you will be able to work on practical examples that showcase the usefulness of min() and max(). Additionally, you will learn how to implement your own versions of min() and max() in pure Python, which will help you understand how these functions work internally.

Getting Started With Python’s min() and max() Functions

The functions min() and max() are powerful tools for finding the smallest and largest values in your data. Here we will explore the different ways to use them effectively.

Calling min() and max() With a Single Iterable Argument

The most common use case for min() and max() is to find the smallest and largest values in an iterable. An iterable can be a list, tuple, set, or any other sequence-like object. Here’s an example:

numbers = [3, 7, 2, 9, 1]
smallest = min(numbers)
largest = max(numbers)
print(smallest, largest) # Output: 1 9

Calling min() and max() With Multiple Arguments

In addition to using an iterable, you can pass multiple arguments to min() and max() directly. This allows you to find the smallest and largest values among a series of regular arguments. Here’s an example:

smallest = min(3, 7, 2, 9, 1)
largest = max(3, 7, 2, 9, 1)
print(smallest, largest) # Output: 1 9

Using min() and max() With Strings and Iterables of Strings

The min() and max() functions can also be used with strings and iterables of strings. When comparing strings, min() and max() determine the smallest and largest values based on lexicographic order. Here are a couple of examples:

my_string = "Python"
smallest = min(my_string)
largest = max(my_string)
print(smallest, largest) # Output: P y
my_list = ["Bob", "Alice", "Charlie"]
smallest = min(my_list)
largest = max(my_list)
print(smallest, largest) # Output: Alice Charlie

Processing Dictionaries With min() and max()

When working with dictionaries, min() and max() compare the keys by default. If you want to find the smallest or largest values based on the dictionary values, you can use the key argument. Here’s an example:

my_dict = {"apple": 3, "banana": 2, "cherry": 5}
smallest = min(my_dict, key=my_dict.get)
largest = max(my_dict, key=my_dict.get)
print(smallest, largest) # Output: banana cherry

Tweaking the Standard Behavior of min() and max() With key and default

Sometimes you might need to customize the behavior of min() and max(). The key argument allows you to specify a function that will be used to extract a comparison key from each element. Additionally, the default argument lets you specify a default value to return if the iterable is empty. Here’s an example:

my_list = [-2, -5, 0, 7, 10]
# Custom key function to find the smallest positive value
smallest_positive = min(my_list, key=lambda x: x if x > 0 else float("inf"))
print(smallest_positive) # Output: 7
# Custom default value to return if the list is empty
largest_empty = max([], default="List is empty")
print(largest_empty) # Output: List is empty

Using min() and max() With Comprehensions and Generator Expressions

Another powerful feature of min() and max() is the ability to use comprehensions and generator expressions as arguments. This allows you to perform complex calculations and filtering before finding the smallest or largest values. Here’s an example:

my_list = [1, -2, 3, -4, 5]
# Find the smallest absolute value from a filtered list
smallest_abs = min(abs(x) for x in my_list if x > 0)
print(smallest_abs) # Output: 1
# Find the largest string by length
my_strings = ["apple", "banana", "cherry"]
largest_string = max((len(s), s) for s in my_strings)[1]
print(largest_string) # Output: banana

Putting Python’s min() and max() Into Action

Now that you have a good understanding of how to use min() and max(), let’s put them into action with some practical examples.

Removing the Smallest and Largest Numbers in a List

numbers = [1, 5, 2, 7, 3]
numbers.remove(min(numbers))
numbers.remove(max(numbers))
print(numbers) # Output: [5, 2, 3]

Building Lists of Minimum and Maximum Values

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# List comprehension to build a list of minimum values from each sublist
min_values = [min(row) for row in matrix]
print(min_values) # Output: [1, 4, 7]
# List comprehension to build a list of maximum values from each sublist
max_values = [max(row) for row in matrix]
print(max_values) # Output: [3, 6, 9]

Clipping Values to the Edges of an Interval

values = [10, 5, 8, 3, 6]
# List comprehension to clip values above 8 to 8 and values below 4 to 4
clipped_values = [min(max(value, 4), 8) for value in values]
print(clipped_values) # Output: [8, 5, 8, 4, 6]

Finding the Closest Points

points = [(2, 5), (4, 3), (1, 8), (6, 4)]
# Find the two closest points based on the Euclidean distance
closest_points = min(points, key=lambda p: (p[0] - 3) ** 2 + (p[1] - 3) ** 2)
print(closest_points) # Output: (4, 3), the closest point to (3, 3)

Identifying Cheap and Expensive Products

products = [
{"name": "Apple", "price": 1.99},
{"name": "Banana", "price": 0.99},
{"name": "Cherry", "price": 2.99},
]
# Find the cheapest and most expensive products based on price
cheapest_product = min(products, key=lambda p: p["price"])
expensive_product = max(products, key=lambda p: p["price"])
print(cheapest_product["name"]) # Output: Banana
print(expensive_product["name"]) # Output: Cherry

Finding Coprime Integer Numbers

import math
a = 21
b = 14
# Find the largest coprime number between a and b
largest_coprime = max(range(1, min(a, b) + 1), key=lambda n: math.gcd(a, b) == 1)
print(largest_coprime) # Output: 7

Timing Different Implementations of Your Code

import time
start_time = time.time()
# Your code here
end_time = time.time()
execution_time = end_time - start_time
print(f"Execution time: {execution_time} seconds")

Exploring the Role of .lt() and .gt() in min() and max()

The min() and max() functions rely on the comparison methods of objects to determine the smallest and largest values. By default, they use the .__lt__() and .__gt__() methods, which stand for “less than” and “greater than,” respectively. These methods allow you to define custom comparison logic for your objects. Here’s an example:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __lt__(self, other):
return self.age < other.age
def __gt__(self, other):
return self.age > other.age
people = [Person("Alice", 25), Person("Bob", 30), Person("Charlie", 20)]
youngest = min(people)
oldest = max(people)
print(youngest.name) # Output: Charlie
print(oldest.name) # Output: Bob

In this example, the Person class defines custom comparison methods to compare objects based on their age attribute. This allows min() and max() to find the youngest and oldest people in the list based on age.

Emulating Python’s min() and max()

To deepen your understanding of how min() and max() work internally, you can try implementing your own versions in pure Python. Here is an example of how you can approach this:

def custom_min(*args, default=None):
if not args:
raise ValueError("min() called with no arguments")
if len(args) == 1:
args = args[0]
if not args:
if default is None:
raise ValueError("arg is an empty sequence")
return default
return sorted(args)[0]
def custom_max(*args, default=None):
if not args:
raise ValueError("max() called with no arguments")
if len(args) == 1:
args = args[0]
if not args:
if default is None:
raise ValueError("arg is an empty sequence")
return default
return sorted(args)[-1]

These custom_min() and custom_max() functions behave similarly to the built-in min() and max() functions but have some additional logic to handle edge cases.

Conclusion

Python’s min() and max() functions are powerful tools for finding the smallest and largest values in your data. Whether you are working with numbers, strings, or other data structures, these functions can help you extract valuable information from your data. By understanding how to use them effectively and even implementing your own versions, you can become a more proficient Python programmer.

Now that you have learned the ins and outs of min() and max(), you can apply this knowledge to various real-world scenarios and enhance your Python programming skills.

Remember to practice and experiment with different use cases to deepen your understanding of these functions. Happy coding!

Tags: basics, python