Python – Row with Minimum difference in extreme values


When it is required to get the row with minimum difference in extreme values, list comprehension, the ‘min’ method and ‘max’ methods are used.

Example

Below is a demonstration of the same

my_list = [[41, 1, 38], [25, 33, 1], [13, 44, 65], [1, 22]]

print("The list is : ")
print(my_list)

my_min_val = min([max(elem) - min(elem) for elem in my_list])

my_result = [elem for elem in my_list if max(elem) - min(elem) == my_min_val]

print("The result is : ")
print(my_result)

Output

The list is :
[[41, 1, 38], [25, 33, 1], [13, 44, 65], [1, 22]]
The result is :
[[1, 22]]

Explanation

  • A list of list is defined and is displayed on the console.

  • The list is iterated over and the difference between maximum and minimum elements is determined.

  • The minimum of this is obtained and assigned to a variable.

  • A list comprehension is used to iterate through the list and see if the difference between the maximum and minimum element is equal to the previously defined variable.

  • This is assigned to a variable.

  • This is displayed as output on the console.

Updated on: 20-Sep-2021

24 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements