- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Advertisements