Computer >> Computer tutorials >  >> Programming >> Python

Find Maximum difference between tuple pairs in Python


When it is required to find the maximum difference between tuple pairs, the 'max' method and the list comprehension can be used.

A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on). A list of tuple basically contains tuples enclosed in a list.

The list comprehension is a shorthand to iterate through the list and perform operations on it.

The 'max' method returns the maximum of values by taking an iterable as argument.

Below is a demonstration of the same −

Example

my_list_1 = [(11, 14), (0, 78), (33, 67), (89, 0)]

print("The list of tuple is : ")
print(my_list_1)
temp_val = [abs(b - a) for a, b in my_list_1]
my_result = max(temp_val)

print("The maximum difference among tuple pairs is : ")
print(my_result)

Output

The list of tuple is :
[(11, 14), (0, 78), (33, 67), (89, 0)]
The maximum difference among tuple pairs is :
89

Explanation

  • A list of tuple is defined and is displayed on the console.
  • The list of tuple is iterated over, and in the pair of elements in the tuple, the first element is subtracted from the first.
  • Its absolute value is taken.
  • It is converted to a list.
  • The 'max' method is used to find the maximum of all elements in the list.
  • This is assigned to a value.
  • It is displayed on the console.