Find Min and Max values in a list of tuples in Python

avatar

Borislav Hadzhiev

Last updated: Jun 27, 2022

banner

Photo from Unsplash

Find Min and Max values in a list of tuples in Python #

To find the min and max values in a list of tuples:

  1. Use the min() and max() functions.
  2. Pass the key argument to the functions.
  3. Select the element in the tuple to be compared.
main.py
my_list = [(100, 1), (100, 2), (100, 3)] # ✅ get min tuple in list of tuples min_tuple = min(my_list, key=lambda tup: tup[1]) print(min_tuple) # 👉️ (100, 1) # ------------------------------------------------------ # ✅ get max tuple in list of tuples max_tuple = max(my_list, key=lambda tup: tup[1]) print(max_tuple) # 👉️ (100, 3)

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

The max function returns the largest item in an iterable or the largest of two or more arguments.

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

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

If the iterable is empty and the default keyword argument is not provided, the functions raise a ValueError.

The key argument specifies a one-argument ordering function like the one used for list.sort().
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)

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

You can also use the key argument to get the min and max values in a list of tuples according to different criteria.

main.py
my_list = [(100, 'a'), (100, 'ab'), (100, 'abc')] # ✅ get value with min length in list of tuples min_tuple = min(my_list, key=lambda tup: len(tup[1])) print(min_tuple) # 👉️ (100, 'a') # ------------------------------------------------------ # ✅ get value with max length in list of tuples max_tuple = max(my_list, key=lambda tup: len(tup[1])) print(max_tuple) # 👉️ (100, 'abc')

We passed the second item in each tuple to the len() function to get the string's length.

The function you provide for the key argument can be used to get the min and max values according to different criteria.

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.