- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

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

# Find Maximum difference pair in Python

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.

## With nlargest

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.

## Example

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)

## Output

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)]

## With combinations and Max()

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.

## Example

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)

## Output

Running the above code gives us the following result −

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

- Related Questions & Answers
- Find pair with maximum difference in any column of a Matrix in C++
- Program to find maximum distance between a pair of values in Python
- Find Maximum difference between tuple pairs in Python
- 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++
- Get minimum difference in Tuple pair in Python
- 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 the Pair with a Maximum Sum in a Matrix using C++
- Find Sum of pair from two arrays with maximum sum in C++
- Python - Maximum difference across lists
- Maximum Length of Pair Chain in C++

Advertisements