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.

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(0, len(my_list_1) - 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

Explanation

  • Two lists are defined and are displayed on the console.

  • The difference between elements of the two lists are taken by iterating through the length of the elements.

  • The absolute difference between the values is taken, and then the maximum of these differences is taken.

  • This is stored in a variable.

  • This is displayed as output on the console.

Updated on: 15-Sep-2021

262 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements