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
Python - Maximum difference across lists
When it is required to find the maximum difference across the lists, the abs() and the max() methods are used to calculate the absolute difference between corresponding elements and find the largest one.
Example
Below is a demonstration of the same −
my_list_1 = [7, 9, 1, 2, 7]
my_list_2 = [6, 3, 1, 2, 1]
print("The first list is :")
print(my_list_1)
print("The second list is :")
print(my_list_2)
my_result = max(abs(my_list_2[index] - my_list_1[index])
for index in range(len(my_list_1)))
print("The maximum difference among the lists is :")
print(my_result)
Output
The first list is : [7, 9, 1, 2, 7] The second list is : [6, 3, 1, 2, 1] The maximum difference among the lists is : 6
Using zip() Method
An alternative approach using zip() to pair corresponding elements −
my_list_1 = [7, 9, 1, 2, 7]
my_list_2 = [6, 3, 1, 2, 1]
my_result = max(abs(a - b) for a, b in zip(my_list_1, my_list_2))
print("Maximum difference using zip():", my_result)
Maximum difference using zip(): 6
How It Works
Two lists are defined and displayed on the console.
The difference between corresponding elements is calculated by iterating through the lists.
The
abs()function ensures we get the absolute difference between values.The
max()function finds the largest difference among all pairs.This maximum difference is stored in a variable and displayed as output.
Conclusion
Use max() with abs() to find the maximum absolute difference between corresponding elements. The zip() method provides a cleaner approach for pairing elements.
