Python Tuple max() Method



The Python Tuple max() method returns the elements from the tuple with maximum value.

Finding the maximum of two given numbers is one of the usual calculations we perform. In general max is an operation where we find the largest value among the given values. For example, from the values “10, 20, 75, 93” the maximum value is 93.

Syntax

Following is the syntax of Python Tuple max() method −

max(tuple)

Parameters

  • tuple − This is a tuple from which max valued element has to be returned.

Return Value

This method returns the elements from the tuple with maximum value.

Example

The following example shows the usage of Python Tuple max() method. Here, two tuples 'tuple1' and 'tuple2' are created. The method performs alphabetical comparison on the string elements of the tuple created. Then the largest element of this tuple is retrieved using max() method.

tuple1, tuple2 = ('xyz', 'zara', 'abc'), (456, 700, 200)
print ("Max value element : ", max(tuple1))
print ("Max value element : ", max(tuple2))

When we run above program, it produces following result −

Max value element :  zara
Max value element :  700

Example

Now let us find the maximum number in a tuple containing only numbers in the example below.

# creating a tuple
tup = (465, 578, 253, 957)
res = max(tup)
# printing the result
print("Maximum element is: ", res)

While executing the above code we get the following output −

Maximum element is:  957

Example

In here, we are creating a tuple 'tup'. This tuple contains equal length elements. So, the max() method is used to retrieve the maximum element among the tuple which is lexicographically largest.

tup = ('DOG', 'Dog', 'dog', 'DoG', 'dOg')
# printing the result
print('Maximum element is: ', max(tup))

Following is an output of the above code −

Maximum element is:  dog

Example

In this example, let us consider a real-time scenario where this method might come in handy. We are creating two tuples: one containing student names and the other containing their marks in the corresponding index. The highest marks are found using the max() method and the corresponding index of the student with the highest marks is retrieved using the index() method. The student bearing the highest marks has to be announced as the topper.

marks = (768, 982, 876, 640, 724)
student = ('Deependra', 'Shobhit', 'Alka', 'Pawan', 'Sam')
rank_1 = max(marks)
name_id = marks.index(max(marks))
print(student[name_id], "ranked first with", rank_1, "marks")

Output of the above code is as follows −

Shobhit ranked first with 982 marks
python_tuples.htm
Advertisements