Python 3 – Tuple max() Method
A tuple is an immutable collection of items, which means once created, its contents cannot be changed. It is a type of data structure in Python programming language that is commonly used to store and manipulate a group of related data items.
The max()
method is a built-in function in Python that returns the largest item in the iterable. In this article, we will explore the max()
method for tuples and how it works.
Syntax of max() Method for Tuples
The max()
method for tuples takes an iterable as an argument and returns the largest item in the tuple. The syntax for using the max()
method for tuples is as follows:
max(iterable, *[, key, default])
- iterable: A tuple or any other iterable object like a list, dictionary, etc.
- *: It represents the tuple unpacking operator.
- key: A function that takes a single argument and returns a value to use for sorting purposes.
- default: The value to return if the iterable is empty.
Let’s understand the above syntax through some examples.
Example 1: Using max() Method for Tuple of Integers
tuple1 = (25, 34, 12, 28, 45)
print(f"Largest element in tuple1 is {max(tuple1)}")
Output:
Largest element in tuple1 is 45
Here, we have created a tuple of integers named tuple1
. We are then passing this tuple as an argument to the max()
method to find the largest element in it. The print()
statement outputs the result of the max()
method.
Example 2: Using max() Method with key Function
tuple2 = ('apple', 'banana', 'mango', 'peach', 'strawberry')
print(f"Longest element in tuple2 is {max(tuple2, key=len)}")
Output:
Longest element in tuple2 is strawberry
Here, we have created a tuple of strings named tuple2
. We are then passing this tuple as an argument to the max()
method along with the len
function as the key
argument. The len()
function is used to determine the length of each string in the tuple, and the max()
method returns the element that has the longest length. The print()
statement outputs the result of the max()
method.
Example 3: Using max() Method with default Value
tuple3 = ()
print(f"Largest element in tuple3 is {max(tuple3, default='Tuple is empty')}")
Output:
Largest element in tuple3 is Tuple is empty
Here, we have created an empty tuple named tuple3
. We are then passing this tuple as an argument to the max()
method along with the default
argument set to Tuple is empty
. As the tuple3
is empty, the default value is returned by the max()
method. The print()
statement outputs the result of the max()
method.
Conclusion
In this article, we learned about the max()
method for tuples in Python programming language. We saw how to use the max()
method with different arguments and examples to find the largest item in a tuple. The max()
method is a simple and useful function that can be used to perform various operations on tuples.