- Related Questions & Answers
- Find pair with maximum difference in any column of a Matrix in C++
- Find pair of rows in a binary matrix that has maximum bit difference in C++
- Find a pair from the given array with maximum nCr value in Python
- Find pair with maximum GCD in an array in C++
- Count ways of choosing a pair with maximum difference in C++
- Find a pair with the given difference in C++
- Find a pair with maximum product in array of Integers in C++
- Queries to find maximum product pair in range with updates in C++
- Find maximum difference between nearest left and right smaller elements in Python
- Maximum Length of Pair Chain in C++
- Probability of a random pair being the maximum weighted pair in C++
- Find original numbers from gcd() every pair in Python
- Find a pair from the given array with maximum nCr value in C++
- Program to find maximum difference of adjacent values after deleting k numbers in python
- Find maximum length Snake sequence in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Data analysis can throw a variety of challenges. In this article we will take a list with numbers as its elements. Then we will find such pairs of elements in the list which has maximum difference in value between them.

The approach here is to first find out all possible combinations of elements and then subtract the second element from the first. Finally apply the nlargest function form heapq module to get those pairs where the difference is maximum.

from itertools import combinations from heapq import nlargest listA = [21, 14, 30, 11, 17, 18] # Given list print("Given list : ",listA) # using nlargest and combinations() res = nlargest(2, combinations(listA, 2), key=lambda sub: abs(sub[0] - sub[1])) # print result print("Pairs with maximum difference are : ",res)

Running the above code gives us the following result −

Given list : [21, 14, 30, 11, 17, 18] Pairs with maximum difference are : [(30, 11), (14, 30)]

Here we also take the same approach as above but we get one pair as a result because we apply the max function which gives us one pair as the result.

from itertools import combinations listA = [21, 14, 30, 11, 17, 18] # Given list print("Given list : ",listA) # using combinations() and lambda res = max(combinations(listA, 2), key = lambda sub: abs(sub[0]-sub[1])) # print result print("Pairs with maximum difference are : ",res)

Running the above code gives us the following result −

Given list : [21, 14, 30, 11, 17, 18] Pairs with maximum difference are : (30, 11)

Advertisements