Get the max value in a Tuple in Python

avatar

Borislav Hadzhiev

Last updated: Jun 26, 2022

banner

Photo from Unsplash

Get the max value in a Tuple in Python #

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

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

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

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

main.py
my_tuple = (15, 45, 30) result = max(my_tuple) print(result) # 👉️ 45

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

main.py
result = max(15, 45, 30) print(result) # 👉️ 45

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 = max((), 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 max value in a list of tuples, pass the key argument to the max() function.

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

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 max value according to the criteria, the third tuple is returned.

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

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

main.py
my_tuple_2 = ('a', 'ab', 'abc') max_length = max(my_tuple_2, key=lambda val: len(val)) print(max_length) # 👉️ 'abc'
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.