Get the min value in a Tuple in Python

avatar

Borislav Hadzhiev

Last updated: Jun 26, 2022

banner

Photo from Unsplash

Get the min value in a Tuple in Python #

Use the min() function to get the min value in a tuple, e.g. min_value = min(my_tuple). The min() function returns the smallest item in an iterable (such as a tuple).

main.py
my_tuple = (1, 3, 5, 7, 9) # ✅ get min value in a tuple min_value = min(my_tuple) print(min_value) # 👉️ 1 # ----------------------------------------- # ✅ get min value in list of tuples my_list = [(100, 1), (100, 2), (100, 3)] min_tuple = min(my_list, key=lambda tup: tup[1]) print(min_tuple) # 👉️ (100, 1) # ----------------------------------------- # ✅ get item with min length in tuple my_tuple_2 = ('a', 'ab', 'abc') min_length = min(my_tuple_2, key=lambda val: len(val)) print(min_length) # 👉️ 'a'

We used the min() function to get the min value in a tuple.

The min function returns the smallest item in an iterable or the smallest of two or more arguments.

main.py
my_tuple = (10, 5, 20) result = min(my_tuple) print(result) # 👉️ 5

The function can also be passed two or more positional arguments.

main.py
result = min(10, 5, 20) print(result) # 👉️ 5

The function takes an optional default keyword argument which is used to specify a value to return if the provided iterable is empty.

main.py
result = min((), default=0) print(result) # 👉️ 0

If the iterable is empty and the default keyword argument is not provided, the function raises a ValueError.

If you need to get the min value in a list of tuples, pass the key argument to the min() function.

main.py
my_list = [(100, 1), (100, 2), (100, 3)] min_tuple = min(my_list, key=lambda tup: tup[1]) print(min_tuple) # 👉️ (100, 1)

The key argument specifies a one-argument ordering function like the one used for list.sort().

We selected the tuple item at index 1 to compare the second item in the tuples.

Since 1 is the min value according to the criteria, the first tuple is returned.

You can use the key argument to get the min value in a tuple according to different criteria.

Here is an example that finds the value with the min length in a tuple.

main.py
my_tuple_2 = ('a', 'ab', 'abc') min_length = min(my_tuple_2, key=lambda val: len(val)) print(min_length) # 👉️ 'a'
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.