Python – Extract list with difference in extreme values greater than K


When it is required to extract list with difference in extreme values greater than K, a list comprehension and the ‘min’ and ‘max’ methods are used.

Below is a demonstration of the same −

Example

 Live Demo

my_list = [[13, 52, 11], [94, 12, 21], [23, 45, 23], [11, 16, 21]]

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

key = 40

my_result = [element for element in my_list if max(element) - min(element) > key]

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

Output

The list is :
[[13, 52, 11], [94, 12, 21], [23, 45, 23], [11, 16, 21]]
The result is :
[[13, 52, 11], [94, 12, 21]]

Explanation

  • A list is defined and displayed on the console.

  • The value for K is defined.

  • A list comprehension is used to iterate over the list, and the difference of minimum and maximum of the element is compared with the key.

  • This result is assigned to a variable.

  • This is the output that is displayed on the console.

Updated on: 06-Sep-2021

145 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements