Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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)
The output of the above code is −
The list is : [[41, 1, 38], [25, 33, 1], [13, 44, 65], [1, 22]] The result is : [[1, 22]]
How It Works
The solution works in two steps:
-
Calculate differences: For each row, compute the difference between maximum and minimum values using
max(elem) - min(elem). -
Find minimum difference: Use
min()to find the smallest difference among all rows. - Filter matching rows: Return all rows where the difference equals the minimum difference found.
Step-by-Step Breakdown
my_list = [[41, 1, 38], [25, 33, 1], [13, 44, 65], [1, 22]]
# Calculate differences for each row
differences = [max(elem) - min(elem) for elem in my_list]
print("Differences for each row:", differences)
# Find the minimum difference
my_min_val = min(differences)
print("Minimum difference:", my_min_val)
# Get rows with minimum difference
my_result = [elem for elem in my_list if max(elem) - min(elem) == my_min_val]
print("Rows with minimum difference:", my_result)
Differences for each row: [40, 32, 52, 21] Minimum difference: 21 Rows with minimum difference: [[1, 22]]
Alternative Approach Using enumerate()
If you need the index of the row with minimum difference ?
my_list = [[41, 1, 38], [25, 33, 1], [13, 44, 65], [1, 22]]
# Find row with minimum difference and its index
min_diff = float('inf')
result_rows = []
result_indices = []
for i, row in enumerate(my_list):
diff = max(row) - min(row)
if diff < min_diff:
min_diff = diff
result_rows = [row]
result_indices = [i]
elif diff == min_diff:
result_rows.append(row)
result_indices.append(i)
print("Rows with minimum difference:", result_rows)
print("Indices:", result_indices)
Rows with minimum difference: [[1, 22]] Indices: [3]
Conclusion
Use list comprehension with min() and max() to find rows with minimum difference between extreme values. The approach efficiently compares differences across all rows and returns matching results.
Advertisements
