Get minimum difference in Tuple pair in Python

PythonServer Side ProgrammingProgramming

When it is required to get the minimum different in a tuple pair from a list of tuples, it can be done using the 'min' method and the list comprehension.

The list comprehension is a shorthand to iterate through the list and perform operations on it. The 'min' method returns the minimum of values among an iterable.

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.

Below is a demonstration of the same −

Example

Live Demo

my_list = [( 67, 78), (39, 34), (23, 52), (99, 69), (78, 2), (11, 0)]

print ("The list is : " )
print(my_list)
temp_val = [abs(b - a) for a, b in my_list]

my_result = min(temp_val)

print("The minimum difference among the pairs of list of tuples is: ")
print(my_result)

Output

The list is :
[(67, 78), (39, 34), (23, 52), (99, 69), (78, 2), (11, 0)]
The minimum difference among the pairs of list of tuples is:
5

Explanation

  • A list of tuples is defined, and displayed on the console.
  • The list is iterated over, and the absolute difference between the second and first element is determined.
  • This value is assigned to a temporary value.
  • The 'min' method is used on this temporary value that gives the minimum value from the data.
  • This is assigned to a variable.
  • This variable is the output that is displayed on the console.
raja
Published on 11-Mar-2021 14:01:04
Advertisements