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
Get minimum difference in Tuple pair in Python
When you have a list of tuples and need to find the minimum difference between pairs of elements, you can use the min() function with list comprehension to efficiently calculate this.
The min() method returns the smallest value from an iterable, while list comprehension provides a concise way to iterate through the list and perform operations. The abs() function ensures we get absolute differences (always positive values).
Example
Let's find the minimum difference between tuple pairs ?
my_list = [(67, 78), (39, 34), (23, 52), (99, 69), (78, 2), (11, 0)]
print("The list is:")
print(my_list)
# Calculate absolute differences between each tuple pair
temp_val = [abs(b - a) for a, b in my_list]
# Find the minimum difference
my_result = min(temp_val)
print("The minimum difference among the pairs of list of tuples is:")
print(my_result)
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
One-Line Solution
You can combine both operations into a single line ?
my_list = [(67, 78), (39, 34), (23, 52), (99, 69), (78, 2), (11, 0)]
# Calculate minimum difference in one line
min_diff = min(abs(b - a) for a, b in my_list)
print("Minimum difference:", min_diff)
Minimum difference: 5
How It Works
The solution works by:
- Iterating through each tuple
(a, b)in the list - Computing
abs(b - a)to get the absolute difference - Using
min()to find the smallest difference among all pairs - The tuple
(39, 34)has difference|34 - 39| = 5, which is minimum
Conclusion
Use list comprehension with abs() and min() to find minimum differences in tuple pairs. The one-line solution using a generator expression is more memory-efficient for large datasets.
