The Wayback Machine - https://web.archive.org/web/20240906192001/https://www.geeksforgeeks.org/python-min-function/
Open In App

Python min() Function

Last Updated : 03 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python min() function returns the smallest of the values or the smallest item in an iterable passed as its parameter.

Example: Find Python min integer from the list

Python
numbers = [23,25,65,21,98]
print(min(numbers))

Output

21

Python min() Function Syntax

min(a, b, c, …, key=func)

The min() function in Python can take any type of object of similar type and return the smallest among them. In the case of strings, it returns lexicographically the smallest value.

Parameters

  • a, b, c, .. : similar type of data.
  • key (optional): A function to customize the sort order

Return

Returns the smallest item.

What is min() Function in Python?

Python min() function is used to find the minimum value. It is the opposite function of max().

You can use this function on any iterable like a string, list, tuple, etc. which makes it very useful.

How to use min() function in Python?

Using min() function in Python is very easy. You just need to pass the list as a parameter in the min function and it will return the minimum number.

Example: We can easily find Python min of two numbers.

Python
print(min(45,56))

Output

45

More Python min() Examples

In this example, we find the minimum element in different reference using Python min().

Example 1: Find Python Min of List

In this example, we are using min() to locate the smallest item in Python in a list.

Python
numbers = [3, 2, 8, 5, 10, 6]
small = min(numbers);

print("The smallest number is:", small)

Output
The smallest number is: 2



Example 2: Find min in List of String

In this example, we are using min() to locate the smallest string in Python in a list.

Python
languages = ["Python", "C Programming", "Java", "JavaScript",'PHP','Kotlin']
small = min(languages)
print("The smallest string is:", small)

Output

The smallest string is: C Programming

Example 3: Minimum Element in a Dictionary

In this example, we are using min() to find the minimum element in a dictionary.

Python
square = {5: 25, 8: 64, 2: 4, 3: 9, -1: 1, -2: 4}

print("The smallest key:", min(square))    # -2

key2 = min(square, key = lambda k: square[k])

print("The smallest value:", square[key2])    # 1

Output
The smallest key: -2
The smallest value: 1



In this article, we discussed the definition, syntax, and examples of the Python min() function. min() function in Python is very versatile and can be used with any iterable.

Hope this article helped you understand how to use the min() function, and you can effectively use it in your projects.

Read More Python Built-in Functions

Similar Reads:

Python min() Function – FAQs

How does min() handle different data types like integers, floats, and strings?

The min() function can compare and find the minimum value among elements of the same type:

  • Integers and floats: It compares numerical values directly.
  • Strings: It compares strings lexicographically (dictionary order).
print(min(3, 1.5, 2))  # Output: 1.5
print(min("apple", "banana", "cherry"))  # Output: "apple"

What happens if we apply min() to an empty sequence?

If you apply min() to an empty sequence without specifying a default value, it raises a ValueError.

print(min([]))  # Raises ValueError: min() arg is an empty sequence

You can avoid this by providing a default value using the default keyword argument.

print(min([], default="No elements"))  # Output: "No elements"

How does min() handle sequences with duplicate minimum values?

If a sequence contains duplicate minimum values, min() returns the first occurrence of the minimum value.

print(min([2, 3, 1, 4, 1]))  # Output: 1 (first occurrence)

How to use min() with tuples and sets?

You can use min() with tuples and sets just as you would with lists.

# Tuples
print(min((5, 3, 9, 1))) # Output: 1

# Sets
print(min({7, 2, 8, 3})) # Output: 2

Can we use min() with custom objects and classes?

Yes, you can use min() with custom objects and classes, but you need to define how the objects should be compared. This is done by implementing comparison methods like __lt__ (less than) in your class.

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def __lt__(self, other):
return self.age < other.age

def __repr__(self):
return f"{self.name} ({self.age})"

p1 = Person("Alice", 30)
p2 = Person("Bob", 25)
p3 = Person("Charlie", 35)

print(min(p1, p2, p3)) # Output: Bob (25)

In this example, min() uses the __lt__ method to compare the Person objects based on their age.



Previous Article
Next Article

Similar Reads

Numpy recarray.min() function | Python
In numpy, arrays may have a data-types containing fields, analogous to columns in a spreadsheet. An example is [(a, int), (b, float)], where each entry in the array is a pair of (int, float). Normally, these attributes are accessed using dictionary lookups such as arr['a'] and arr['b']. Record arrays allow the fields to be accessed as members of th
4 min read
Python String Methods | Set 3 (strip, lstrip, rstrip, min, max, maketrans, translate, replace &amp; expandtabs())
Some of the string methods are covered in the below sets.String Methods Part- 1 String Methods Part- 2More methods are discussed in this article1. strip():- This method is used to delete all the leading and trailing characters mentioned in its argument.2. lstrip():- This method is used to delete all the leading characters mentioned in its argument.
4 min read
List Methods in Python | Set 1 (in, not in, len(), min(), max()...)
List methods are discussed in this article. 1. len() :- This function returns the length of list. List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1] print(len(List)) Output: 10 2. min() :- This function returns the minimum element of list. List = [2.3, 4.445, 3, 5.33, 1.054, 2.5] print(min(List)) Output: 1.054 3. max() :- This function returns the maximum eleme
2 min read
Python String | min()
min() is an inbuilt function in Python programming language that returns the minimum alphabetical character in a string. Syntax: min(string) Parameter: min() method takes a string as a parameter Return value: Returns a character which is alphabetically the lowest character in the string. Below is the Python implementation of the method min() # pyth
1 min read
Python | Pandas Series.min()
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.min() function return the mode of the underlying data in the given Series objec
2 min read
Python | Pandas dataframe.min()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.min() function returns the minimum of the values in the given object. If the input is a series, the method will return
2 min read
Python | Pandas Index.min()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.min() function returns the minimum value of the Index. The function works with both numerical as well as the string type ob
2 min read
Python | Pandas TimedeltaIndex.min
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas TimedeltaIndex.min() function return the minimum value of the TimedeltaIndex object or minimum along an axis. Syntax : TimedeltaI
2 min read
Use of min() and max() in Python
Prerequisite: min() max() in Python Let's see some interesting facts about min() and max() function. These functions are used to compute the maximum and minimum of the values as passed in its argument. or it gives the lexicographically largest value and lexicographically smallest value respectively, when we passed string or list of strings as argum
2 min read
Python | Numpy matrix.min()
With the help of Numpy matrix.min() method, we can get the minimum value from given matrix. Syntax : matrix.min() Return : Return minimum value from given matrix Example #1 : In this example we can see that we are able to get the minimum value from a given matrix with the help of method matrix.min(). # import the important module in python import n
1 min read
SymPy | Permutation.min() in Python
Permutation.min() : min() is a sympy Python library function that returns the minimum value in the permutation. Syntax : sympy.combinatorics.permutations.Permutation.min() Return : minimum value in the permutation Code #1 : min() Example # Python code explaining # SymPy.Permutation.min() # importing SymPy libraries from sympy.combinatorics.partitio
1 min read
Python | Min/Max value in float string list
Sometimes, while working with a Python list, we can have a problem in which we need to find min/max value in the list. But sometimes, we don't have a natural number but a floating-point number in string format. This problem can occur while working with data, both in web development and Data Science domain. Let's discuss a way in which this problem
6 min read
Python | Max/Min value in Nth Column in Matrix
Sometimes, while working with Python Matrix, we may have a problem in which we require to find the minimum and maximum value of a particular column. This can have a possible application in day-day programming and competitive programming. Let's discuss certain ways in which this task can be performed. Method 1: Using max()/min() + zip() This task ca
7 min read
Python | Decimal min() method
Decimal#min() : min() is a Decimal class method which compares the two Decimal values and return the min of two. Syntax: Decimal.min() Parameter: Decimal values Return: the min of two. Code #1 : Example for min() method # Python Program explaining # min() method # loading decimal library from decimal import * # Initializing a decimal value a = Deci
2 min read
Min Heap in Python
A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. Mapping the elements of a heap into an array is trivial: if a node is stored at index k, then its left child is stored at index 2k + 1 and its right child at index 2k + 2 for 0 based indexing and for 1 b
5 min read
Python Tuple - min() Method
While working with tuples many times we need to find the minimum element in the tuple, and for this, we can also use min(). In this article, we will learn about the min() method used for tuples in Python. Syntax of Tuple min() MethodSyntax: min(object) Parameters: object: Any iterable like Tuple, List, etc. Return type: minimum element from the tup
2 min read
max() and min() in Python
This article brings you a very interesting and lesser-known function of Python, namely max() and min(). Now when compared to their C++ counterpart, which only allows two arguments, that too strictly being float, int or char, these functions are not only limited to 2 elements, but can hold many elements as arguments and also support strings in their
3 min read
Max and Min date in Pandas GroupBy
Prerequisites: Pandas Pandas GroupBy is very powerful function. This function is capable of splitting a dataset into various groups for analysis. Syntax: dataframe.groupby([column names]) Along with groupby function we can use agg() function of pandas library. Agg() function aggregates the data that is being used for finding minimum value, maximum
1 min read
Pandas - GroupBy One Column and Get Mean, Min, and Max values
We can use Groupby function to split dataframe into groups and apply different operations on it. One of them is Aggregation. Aggregation i.e. computing statistical parameters for each group created example - mean, min, max, or sums. Let's have a look at how we can group a dataframe by one column and get their mean, min, and max values. Example 1: i
2 min read
PyQtGraph – Getting Quick Min Max of Image View
In this article, we will see how we can get the min-max value of data of the image view object in PyQTGraph. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video,
4 min read
How to select min and max from table by column score in SQLAchemy?
In this article, we are going to fetch min and max values from column scores in the SQL table using the SQLAlchemy module. SQLAlchemy is an awesome and easy-to-use python module to connect with SQL and use the features and powers of SQL in python. Here, we are provided with a table that has a column named "score" and our task is to find out the max
3 min read
Wand function() function in Python
function() function is similar to evaluate function. In function() function pixel channels can be manipulated by applies a multi-argument function to pixel channels. Following are the list of FUNCTION_TYPES in Wand: 'undefined''arcsin''arctan''polynomial''sinusoid' Syntax : wand.image.function(function, arguments, channel) Parameters : ParameterInp
1 min read
Python - Call function from another function
Prerequisite: Functions in Python In Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems. In this article, we will learn how can we call a defined function from another function with the help of multiple examples.  What is Calling a Function
5 min read
Returning a function from a function - Python
Functions in Python are first-class objects. First-class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. Properties of first-class functions: A function is an instance of the Object type.You can store the function in a variable.You can pass the functi
4 min read
Python math.sqrt() function | Find Square Root in Python
sqrt() function returns square root of any number. It is an inbuilt function in Python programming language. In this article, we will learn more about the Python Program to Find the Square Root. sqrt() Function We can calculate square root in Python using the sqrt() function from the math module. In this example, we are calculating the square root
3 min read
wxPython - GetField() function function in wx.StatusBar
In this article we are going to learn about GetField() function associated to the wx.GetField() class of wxPython. GetField() function Returns the wx.StatusBarPane representing the n-th field. Only one parameter is required, that is, field number in status bar. Syntax: wx.StatusBar.GetField(self, n) Parameters: Parameter Input Type Description n in
1 min read
How to write an empty function in Python - pass statement?
In C/C++ and Java, we can write empty function as following // An empty function in C/C++/Java void fun() { } In Python, if we write something like following in Python, it would produce compiler error. # Incorrect empty function in Python def fun(): Output : IndentationError: expected an indented block In Python, to write empty functions, we use pa
1 min read
Ways to sort list of dictionaries by values in Python - Using lambda function
In this article, we will cover how to sort a dictionary by value in Python. Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications ranging from competitive domain to developer domain(e.g. handling JSON data). Having the knowledge to sort dictionaries according to their values can
2 min read
Python Numbers | choice() function
choice() is an inbuilt function in Python programming language that returns a random item from a list, tuple, or string. Syntax: random.choice(sequence) Parameters: sequence is a mandatory parameter that can be a list, tuple, or string. Returns: The choice() returns a random item. Note:We have to import random to use choice() method. Below is the P
1 min read
Python | askopenfile() function in Tkinter
While working with GUI one may need to open files and read data from it or may require to write data in that particular file. One can achieve this with the help of open() function (python built-in) but one may not be able to select any required file unless provides a path to that particular file in code. With the help of GUI, you may not require to
2 min read
Practice Tags :