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
Find Maximum difference between tuple pairs in Python
When it is required to find the maximum difference between tuple pairs, the max() method and list comprehension can be used.
A list can store heterogeneous values (data of any type like integers, floats, strings, etc.). A list of tuples contains tuples enclosed in a list.
List comprehension provides a shorthand way to iterate through a list and perform operations on it. The max() method returns the maximum value from an iterable.
Example
Below is a demonstration of finding the maximum difference between tuple pairs ?
my_list_1 = [(11, 14), (0, 78), (33, 67), (89, 0)]
print("The list of tuple is:")
print(my_list_1)
temp_val = [abs(b - a) for a, b in my_list_1]
my_result = max(temp_val)
print("The maximum difference among tuple pairs is:")
print(my_result)
The list of tuple is: [(11, 14), (0, 78), (33, 67), (89, 0)] The maximum difference among tuple pairs is: 89
How It Works
The solution works in the following steps ?
- A list of tuples is defined and displayed on the console
- The list is iterated using list comprehension, and for each tuple pair (a, b), the absolute difference
abs(b - a)is calculated - All differences are collected in a new list
temp_val - The
max()method finds the maximum value from all differences - The result is displayed on the console
Alternative Method Using max() with Generator
You can also find the maximum difference directly without creating an intermediate list ?
my_list_1 = [(11, 14), (0, 78), (33, 67), (89, 0)]
print("The list of tuple is:")
print(my_list_1)
my_result = max(abs(b - a) for a, b in my_list_1)
print("The maximum difference among tuple pairs is:")
print(my_result)
The list of tuple is: [(11, 14), (0, 78), (33, 67), (89, 0)] The maximum difference among tuple pairs is: 89
Key Points
- Use
abs()to get the absolute difference between two numbers - List comprehension provides a concise way to process all tuple pairs
- Generator expressions with
max()are more memory-efficient than creating intermediate lists - The method works for any number of tuple pairs in the list
Conclusion
Finding the maximum difference between tuple pairs can be efficiently done using list comprehension with abs() and max() functions. The generator expression approach is more memory-efficient for large datasets.
